Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Type error Exception Value: 'Profile' object is not iterable
Not sure what's going wrong here. IF two users have both voted yes to each other, hence both having a vote attribute of True, I am attempting to add both of them to my matches database. But it's not working and I'm not clear why the Profile object is not iterbale. It works fine in my other methods when I try to get it this sort of way. traceback Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/papichulo/Documents/DatingAppCustom/dating_app/views.py", line 144, in nice return create_vote(request, profile_id, True) File "/Users/papichulo/Documents/DatingAppCustom/dating_app/views.py", line 167, in create_vote npm = Profile.objects.get(request.user) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/query.py", line 399, in get clone = self.filter(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/query.py", line 892, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/query.py", line 910, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1290, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1318, in _add_q split_subq=split_subq, simple_col=simple_col, File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1187, in build_filter arg, value = filter_expr File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/django/utils/functional.py", line 257, in inner return func(self._wrapped, *args) TypeError: … -
After successfully installing mysql and mysql workbench i get this error message each time i run the pip install mysql-python command on virtualenv
ERROR: Command errored out with exit status 1: command: /Users/ebrima/Documents/djangoapp/computerinventory/venv/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/jb/4wfxz94x599f8rnhtgkbs92c0000gn/T/pip-install-EYWqPv/mysql-python/setup.py'"'"'; file='"'"'/private/var/folders/jb/4wfxz94x599f8rnhtgkbs92c0000gn/T/pip-install-EYWqPv/mysql-python/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' install --record /private/var/folders/jb/4wfxz94x599f8rnhtgkbs92c0000gn/T/pip-record-QYXGl9/install-record.txt --single-version-externally-managed --compile --install-headers /Users/ebrima/Documents/djangoapp/computerinventory/venv/include/site/python2.7/mysql-python cwd: /private/var/folders/jb/4wfxz94x599f8rnhtgkbs92c0000gn/T/pip-install-EYWqPv/mysql-python/ -
Unable to trigger Ajax click function in Django
Trying to update a model based on which download link was pressed in Django. Please see current code below, so fair it doesn't appear to be logging to console either. From 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> <br> <a class="btn" id="download" href="{{ y.highlight.url }}" data-id="{{ y.highlight_id }}" download>Download</a> </div> {% endif %} {% endfor %} </div> </div> {% endif %} {% endfor %} <script type="text/javascript"> $("#download").click(function() { console.log( $(this).attr("data-id") ); var catid; catid = $(this).attr("data-id"); $.ajax({ type:"POST", url: "/downloaded", data: { highlight_id: catid }, success: function( data ) { console.log(data) } }) }) </script> From views.py def downloaded(request): if request.method == 'POST': highlight_id = request.GET('highlight_id') downloadedvideo = Highlight.objects.get(pk=highlight_id) downloadedvideo.used = True downloadedvideo.save() return else: return Any help is greatly appreciated! -
Django generic detail view must be called with an object pk or a slug but my URL has a PK already
AttributeError at /mini_fb/profile/1/delete_status/14 Generic detail view DeleteStatusMessageView must be called with either an object pk or a slug in the URLconf. Isn't my PK 1 and 14 already in the URL? Why am I getting this error? <a href="{% url 'delete_status' profile_pk=profile.pk status_pk=x.pk %}">delete</a> class DeleteStatusMessageView(DeleteView): '''A class for the view for deleting status messages.''' template_name = 'mini_fb/delete_status_message.html' queryset = StatusMessage.objects.all() def get_context_data(self, **kwargs): '''Return a dictionary with context data for this template to use.''' context = super(DeleteStatusMessageView, self).get_context_data(**kwargs) st_msg = StatusMessage.objects.get(pk=self.kwargs['status_pk']) context['st_msg'] = st_msg return context # return the dictionary -
User Serializer is showing null in AJAX fetch but shows data in DRF
I have below the details of my serializer for the current user serializers.py class UserDetailSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'id', 'username', 'email', 'first_name', 'last_name', ] views.py class UserViewSet(APIView): def get(self, request): serializer = UserDetailSerializer(request.user) return Response(serializer.data) urls.py urlpatterns = [ path('admin/', admin.site.urls), url(r'^user/', accounts_views.UserViewSet.as_view()), ] going to http://localhost:8000/user/ shows the proper json/api data: { "id": 1, "username": "stormadmin", "email": "", "first_name": "", "last_name": "" } but when I try to use ajax to fetch the data: async getUser() { const response = await fetch('http://127.0.0.1:8000'+'/user/'); const resData = await response.json(); return resData; } I get this instead: {id: null, username: ""} My question is, how do I get the data I want with an AJAX call? Or is there a better way to do this? -
How to return a template from a function without the request argument?
I am not sure if this makes any sense but I am trying to figure out a way to get a function without request argument to return an HTML template. The code below will help you better understand my point. views.py def home(request): global running, row_count, thread if request.method == 'POST': row_count = 0 thread = threading.Thread(target=fun) thread.daemon = True thread.start() running = True return render(request, 'scraper/home.html', {'countries': countries, 'running': running}) else: return render(request, 'scraper/home.html') def fun(): global row_count, finished, thread while True: row_count += 5 if row_count == 15: finished = True thread.join() return time.sleep(5) What I am trying to achieve is to reflect that finished=Truein my 'scraper/home.html/ template. I want to make an element in my template based on the value of finished. Something like this: scraper/home.html {% if finished %} <p>Finished!</p> {% endif %} I'll appreciate your help on this. Thanks -
Django schema explorer simple recursive algorithm - confused by results / how to fix
I am using Django and have a couple of use cases for which the ability for objects to trace their relationships through several models is required. I don't want to hand-code this functionality for every model. Some example models: class Project(models.Model): project_name = models.CharField(max_length=200, default="development_project") class Question(models.Model): project = models.ForeignKey(Project, default=1, on_delete=models.CASCADE) question_text = models.CharField(max_length=200, default="question text") class Extra(models.Model): extended_q = models.ForeignKey(Question, default=1, on_delete=models.CASCADE) summary_of = models.ForeignKey(Question, default=1, on_delete=models.CASCADE) content = models.CharField(max_length=200, default="simple summary") class Answer(models.Model): question = models.ForeignKey(Question, default=1, on_delete=models.CASCADE) user = models.ForeignKey(User, default=1, on_delete=models.CASCADE) Using models as nodes of a network and relationships as edges, this seems like it should be manageable, but for some complexity where there are 'redundant' edges - do we permit an Extra to summarise Answers from a different project? my use cases will be: a models.Manager class that can act as the default manager for a sub-class of Django apps that work together in a unified site and help do the sort of row-separating management that will keep users, even in the admin, from getting under each others feet. an overall app using ContentTypes that can help the user build datasets and organise tables for dataframes (taking fks and making them appropriate category … -
Label and input value overlaps with django-material and datepicker
So the idea is that I need a pop-up and in that pop-up there should be a form in which you have to choose the date, so the pop-up have a Form object with a TextField that emulates the a date input to use the datepicker of material, the problem comes with the label of that input that overlaps with the input itself like this. I tried using javascript to add the class "active" to the label when you click the input because that is what triggers the label to go up but it doesn't recognize it and doesnt apply the class. The html renders like this: <div class="input-field col s12 required" id="id_fecha_cobro_container"> <i class="material-icons prefix">insert_invitation</i><input id="id_fecha_cobro" name="fecha_cobro" type="date"> <label for="id_fecha_cobro">Fecha de Cobro</label> </div> This is the modal in django: {% block change_form %} {% form %} {% part form.fecha_cobro prefix %}<i class="material-icons prefix">insert_invitation</i>{% endpart %} {% endform %} {% prepopulated_fields_js %} {% endblock %} This is the form class: class AvisoVacacionForm(forms.Form): fecha_cobro = forms.DateField(label="Fecha de Cobro", required=True, widget=forms.TextInput(attrs={'type': 'date'})) def __init__(self, *args, **kwargs): super(AvisoVacacionForm, self).__init__(*args, **kwargs) This is what I've tried using javascript: $('#id_fecha_cobro').click(function(){ $("label[for='id_fecha_cobro']").addClass("active") }); -
I can't sort the date in the dictionary
I want to sort by the dictionary in my hand both by key and by year / month in it, but I could not {'120000.0': [['2020/01', 97000.0], ['2020/03', 98000.0], ['2020/02', 'null']], '150000.0': [['2020/01', 113750.0], ['2020/02', 97875.0], ['2020/03', 'null']], '180000.0': [['2020/02', 105083.33333333333], ['2020/03', 'null'], ['2020/01', 'null']], '30000.0': [['2020/02', 129000.0], ['2020/03', 179500.0], ['2020/01', 'null']], '60000.0': [['2020/02', 145700.0], ['2020/03', 155250.0], ['2020/01', 'null']], '90000.0': [['2020/02', 135000.0], ['2020/03', 158000.0], ['2020/01', 'null']]} I want to: { '30000.0': [['2020/01', 'null'],['2020/02', 129000.0], ['2020/03', 179500.0] ], '60000.0': [['2020/01', 'null'],['2020/02', 145700.0], ['2020/03', 155250.0] ], .... } -
integrity error: UNIQUE constraint failed: dating_app_uservote.user_id, dating_app_uservote.voter_id Django
Not sure what's going wrong here. IF two users have both voted yes to each other, hence both having a vote attribute of True, I am attempting to add both of them to my matches database. But it's not working and I'm not clear why. views.py/create_vote def create_vote(request, profile_id, vote): profile = Profile.objects.get(pk=profile_id) UserVote.objects.create( user=profile, voter=request.user, vote=vote ) if vote: if UserVote.objects.filter( user = request.user, voter=profile, vote=True ).count(): npm = Profile.objects.get(user=request.user) npm.matches.add(User.objects.get(username=profile.username)) npm = Profile.objects.get(user=profile) npm.matches.add(User.objects.get(username=request.user)) npm.save() return render(request, 'dating_app/matches.html', dict( match=profile, )) return redirect('dating_app:mingle') models.py class ProfileManager(BaseUserManager): def create_user(self, username, email,description,photo, password=None): if not email: raise ValueError("You must creat an email") if not username: raise ValueError("You must create a username!") if not description: raise ValueError("You must write a description") if not photo: raise ValueError("You must upload a photo") user = self.model( email=self.normalize_email(email), username = username, description= description, photo= photo, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email,description,photo, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, description=description, photo=photo, ) user.is_admin=True user.is_staff=True user.is_superuser=True user.save(using=self._db) return user class Profile(AbstractBaseUser): class Meta: swappable = 'AUTH_USER_MODEL' email = models.EmailField(verbose_name="email") username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = … -
MOD_WSGI Apache2 You don't have permission to access this resource
I am working on deploying a Django project with apache2 and MOD_WSGI. When I run the server, I am unable to access the website and I get the error on the site, Forbidden You don't have permission to access this resource. Apache/2.4.29 (Ubuntu) Server at testnexusstudy.com Port 8081 I have set up everything I think I need like the conf file, <VirtualHost *:8081> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined #Include conf-available/serve-cgi-bin.conf Alias /static /root/StudBud1/static <Directory /root/StudBud1/static> Require all granted </Directory> Alias /media /root/StudBud1/media <Directory /root/StudBud1/media> Require all granted </Directory> <Directory /root/StudBud1/StudBud1> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /root/StudBud1/StudBud1/wsgi.py WSGIDaemonProcess StudBud1 python-path=/root/StudBud1 WSGIProcessGroup StudBud1 </VirtualHost> I have given all the permissions I thought were required for apache and here is my ls -la drwxrwxr-x 12 root www-data 4096 Apr 5 19:36 StudBud1 -rw-rw-r-- 1 root www-data 204800 Apr 5 19:36 db.sqlite3 Hopefully, some of you have experience with this type of error. -
Can't redirect to category list url - django
I'm so sorry for this silly issue, I'm learning django so I might have these issues, please take a look at my codes actually i can't figure out how can i redirect to category list page but url is working fine i just can't able to add correct redirect url by id into href tag :( html <div class="widget widget-catgs"> <h3 class="widget-title">Categories</h3> <ul> {% for cat in category %} <li> <a href="**{% url 'category-list' property.category.id %}**" title=""><i class="la la-angle-right"></i><span>{{ cat.category__title }}</span></a> <span>{{ cat.category__title__count }}</span> </li> {% endfor %} <!-- <li> <a href="#" title=""><i class="la la-angle-right"></i><span>Condo</span></a> <span>15</span> </li> <li> <a href="#" title=""><i class="la la-angle-right"></i><span>Townhouse</span></a> <span>4</span> </li> <li> <a href="#" title=""><i class="la la-angle-right"></i><span>Coop</span></a> <span>1</span> </li> --> </ul> </div> views.py def property_by_category(request, category_id): property_list = Property.objects.all() category = get_object_or_404(Category, pk=category_id) category_list = Property.objects.filter(category=category) context = { 'category_list': category_list, 'category_name': category, 'property': property_list } return render(request, 'property/property-category.html', context) urls.py urlpatterns = [ path('', views.property, name='property-page'), path('details/<int:property_id>', views.property_details, name='property-details'), path('category/<int:category_id>', views.property_by_category, name='category-list'), path('add-property/', views.add_property, name='add-property'), ] -
How to show images using Lightbox in Django
I need your little help. I have set up everything according to the course that I am following but I am not getting images shown as in the course. Here is the issue: I have fetched some images from database and I want to show them using lightbox. I did everything right but images are not showing. My views.py from django.shortcuts import render, get_object_or_404 from django.core.paginator import Paginator from .models import Listing def listing(request, listings_id): listing = get_object_or_404(Listing, pk=listings_id) context = { 'listing': listing } return render(request, 'listings/listing.html', context) My listing.html {% extends 'base.html' %} {% load humanize %} {% block content %} <!-- Listing --> <section id="listing" class="py-4"> <div class="container"> <a href="{% url 'listings' %}" class="btn btn-light mb-4">Back To Listings</a> <div class="row"> <div class="col-md-9"> <!-- Home Main Image --> <img src="{{ listing.photo_main.url }}" alt="" class="img-main img-fluid mb-3"> <!-- Thumbnails --> <div class="row mb-5 thumbs"> <div class="col-md-2"> <a href="{{ listing.photo_1.url }}" data-lightbox="home-images"> <img src="{{ listing.photo_1.url }}" alt="" class="img-fluid"> </a> </div> <div class="col-md-2"> <a href="{{ listing.photo_2.url }}" data-lightbox="home-images"> <img src="{{ listing.photo_2.url }}" alt="" class="img-fluid"> </a> </div> <div class="col-md-2"> <a href="{{ listing.photo_3.url }}" data-lightbox="home-images"> <img src="{{ listing.photo_3.url }}" alt="" class="img-fluid"> </a> </div> <div class="col-md-2"> <a href="{{ listing.photo_4.url }}" data-lightbox="home-images"> <img src="{{ listing.photo_4.url … -
Build an API with Django that display data based on user input
I am struggling with the structure of my api supposed to display a chart from a model primary key. The underlying issue that I have is to write a view that render attributes from the same model as the PK entered by the user and then pass it along with Ajax view.py class forecast(APIView): def get(self, request, *args, **kwargs): query = request.GET.get('search_res', None) data = {} if query and request.method == 'GET': reference = Item.objects.filter(reference = query) forecast1 = Item.objects.filter(reference = query).values('demand_30_jours') forecast2 = Item.objects.filter(reference=query).values('Lt2') forecast3 = Item.objects.filter(reference=query).values('Lt3') data.update({'reference': reference, 'forecastdata': [forecast1,forecast2,forecast3] }) return Response(data) and here is my graph on the html page <script> $(document).ready(function() { var endpoint = 'api/chart/forecast' var forecastdata = [] var reference = [] ; $.ajax({ method: "GET", url: endpoint, data: {'search_res' : $('search_res').val(),}, success: function (data) { reference = data.reference forecastdata = data.forecastdata setChart() }, error: function (error_data) { console.log(error_data) } } ) function setChart(){ var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'scatter', data: { labels: reference, datasets: [{ label: 'item demand planning', data: forecastdata, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, … -
Bootstrap caroussel not showing at all in home page (wagtail)
{# templates/home/home_page.html #} {% extends "base.html" %} {% load wagtailcore_tags wagtailimages_tags %} {% block content %} {% image self.banner_image width-3560 as img %} <div class="jumbotron" style="background-image: url('{{ img.url }}'); min-height: 400px; height: 40vh; background-size: cover; background-position: center top; display: flex; flex-direction: column; justify-content: center;"> <h1 class="display-4">{{ self.banner_title }}</h1> <div class="lead">{{ self.banner_subtitle|richtext }}</div> {% if self.banner_cta %} <a class="btn btn-primary btn-lg" href="#" role="button">@todo</a> {% endif %} </div> {# Example of an Orderable from home/models.py #} <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> {% for loop_cycle in self.carousel_images.all %} {% image loop_cycle.carousel_image fill-900x400 as img %} <div class="carousel-item{% if forloop.counter == 1 %} active{% endif %}"> <img src="{{ img.url }}" class="d-block w-100" alt="{{ img.alt }}"> </div> {% endfor %} </div> <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> {% for block in page.content %} {% include_block block %} {% endfor %} {% endblock %} -
HTTPConnectionPool(host='0.0.0.0', port=5000): Max retries exceeded with url
I am encountering this error, when i try to make a call to a service that is deployed using docker-compose on port 5000 from a django application also deployed using docker-compose on port 8000. I am also using nginx. ConnectionError at /documents/ HTTPConnectionPool(host='localhost', port=5000): Max retries exceeded with url: /api/documents (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x7f976607f290>: Failed to establish a new connection: [Errno 111] Connection refused')) Here's the request object right before the request is made kwargs {'data': None, 'files': {'file': ('XXX', <InMemoryUploadedFile: XXX.pdf (application/pdf)>, 'application/pdf', {})}, 'headers': {'Authorization': 'Token token=XXX', 'Content-Type': 'application/pdf', 'PSPDFKit-API-Version': '2020.1.3'}, 'json': None} method 'post' session <requests.sessions.Session object at 0x7f954da972d0> url 'http://127.0.0.1:5000/api/documents' Here are the relevant files docker-compose version: '3.7' services: web: build: context: ./www dockerfile: Dockerfile.prod command: gunicorn app.wsgi:application --bind 0.0.0.0:8000 volumes: - ./www:/usr/src/app - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles expose: - 8000 env_file: env.prod depends_on: - db db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: env.prod nginx: build: ./nginx volumes: - static_volume:/home/app/web/staticfiles - media_volume:/home/app/web/mediafiles ports: - 1337:80 depends_on: - web pspdfkit: image: "pspdfkit/pspdfkit:2020.1" environment: PGUSER: XXX PGPASSWORD: XXX PGDATABASE: XXX PGHOST: db PGPORT: 5432 # Activation key for your PSPDFKit Server installation. ACTIVATION_KEY: XXXX # Secret token used for authenticating API requests. API_AUTH_TOKEN: XXXX # Base key … -
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) …