Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Querysets on views or on Model Managers DJANGO
thanks for your time. Some days ago a guy explained me that on ruby on rails the querys are done on models. because it gets already saved at your data before be requested on views and the query. by the way i've learned and had been working until now, i'm setting the query on views.py and passing, through a context variable. So i started to read about Model.Manager and still didn't find a answer to wich way is better: 1-querys made on views 2-querys made by simple functions on models 3-querys made on models.Manager class for each model -
Django backend Vue.js frontend fetch data with axios doesnt work
Im trying to build a simple todo app with a django rest framework as backend and a Vue.js frontend. Now i'm trying to fetch my backend data with axios but it doesnt work.Both application are on my localhost. The Django backend listens on port 8000 and the Vue.js app listens on port 8080 this is my code: Django: from django.shortcuts import render from django.http import JsonResponse from rest_framework.decorators import api_view from rest_framework.response import Response from .models import Task from .serializers import TaskSerializer @api_view(['GET']) def taskList(request): task = Task.objects.all() serializer = TaskSerializer(task, many=True) return Response(serializer.data) serializer.py from rest_framework import serializers from .models import Task class TaskSerializer(serializers.ModelSerializer): class Meta: model = Task fields = '__all__' settings.py INSTALLED_APPS = [ .... 'api.apps.ApiConfig', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', ........ 'django.middleware.common.CommonMiddleware', CORS_ORIGIN_WHITELIST = [ "http://localhost:8080", ] Vue.js: ....... <script> ..... created() { axios .get("http://localhost:8000/task-list") .then(res => res.json) .then(data => console.log(data)) .catch(err => console.log(err)); } .... <script> i did a lot of research and watched some youtube tutorials. I installed django-core-headers and put it in my installed apps and added the middleware and added the corse origin whitelist for the Vue.js app. if i try it with postman or with fetch everything works fine. … -
How to add image styling to CKEditor in Django?
I have created a basic django blog. I am using the RichTextUploadingField() for the body using the CK Editor. However, the problem is that the images uploaded using CK Editor are rigid and do not adjust to the screen size like other images on my blog. Please help me out. -
Django: OperationalError: no such column: User_profile.user_id
I am a beginner working on my first "independent" project without tutorial guidance. I have been working on a two password confirmation form for my registration page, without utilizing the django.contrib.auth.forms UserCreationForm. I have my Profile model with one attribute of 'user' which is a OneToOneField with the django.contrib.auth.models User model. For some reason, after I fill out my registration form from the front end and check the profiles group, the OperationalError pops up. This is not the first time I have had a 'no such column.' Can someone help? Would be greatly appreciated. My User/form.py, from django import forms from django.contrib.auth.models import User class UserRegisterForm(forms.ModelForm): password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'password'] def clean_password2(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords do not match") return password2 def save(self, commit=True): user = super().save(commit=False) user.set_password(self.cleaned_data['password1']) if commit: user.save() return user My User/views.py, register view, which is my registration form. def register(request): form = UserRegisterForm(request.POST or None) if form.is_valid(): user = form.save(commmit=False) user = form.save() raw_password = form.cleaned_data.get('password1') user = authenticate(request, password=raw_password) if user is not None: login(request, user) return … -
django admin table wants another row of showing total amount of each column
I'd like to show the query results particularly total amount of each column here on my django admin page, building a postgresql as its database. I don't want an application so I'm not writing any views or htmls - using only the default htmls for admin page. And also the results better be interactive with filtering actions. I'm very new to django and I apologize if I'm out of points. Thanks. -
How to change timer for every single post in django
For every item in items I want to have a timer. I made a timer using javascript and I can show the timer for every single item. But when I want to show all the items in home page the timer is shown just for the last item. Is there any way to show the timer for all the items? <div class="row m0 p0 justify-content-center"> {% for item in items %} <div class="col-12 col-xs-6 col-md-4 card-item p0"> <div class="img-container"> <img class="rounded img-fluid img-thumbnail" src="{{MEDIA_URL}}{{ item.image }}" /> <div class="sold-img-item"></div> {% if item.sold == 1 %} <div class="sold">Sold <div class="sold-price"><span>{{item.highest_bid_offer}} €</span></div> </div> {% endif%} </div> <h5 class="no-flow capital "><b>{{item.title}}</b></h5> <div class="no-flow"><strong>Seller :</strong> {{item.seller}}</div> <div class="no-flow"> <strong>Initial Price :</strong> <span>{{item.price}} €</span> </div> <input type="hidden" id="auction_status" name="auction_status" value="{{ item.auction_status }}"/> <input type="hidden" id="end-time-fix" name="end-time-fix" value="{{item.auction_end_time}}"/> <div class="timer-small" id="timer-small"> <div class="timer-small" id="days-small"></div> <div class="timer-small" id="hours-small"></div> <div class="timer-small" id="minutes-small"></div> <div class="timer-small" id="seconds-small"></div> </div> <a class="divLinkkk" href="{% url 'item_detail' item.id %}"></a> </div> {% endfor %} </div> -
ImportError: No module named rest_framework on running collectstatic
I found many questions with the same error, but none were addressing the actual cause of my problem so I am posting this. I am facing the issue in my (digital ocean) Linux production server. I have python 3.5.2 in virtualenv, and python2.7.12 in the machine. I have installed djangorestframework in virtualenv using command pip3 install djangorestframework But did not install it in the actual machine (on 2.7) On running collectstatic command inside virtualenv I am getting the following error. It seems to be looking for the package in python2.7 and not inside virtualenv. (venv) myname@server:/www/site$ sudo python manage.py collectstatic Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named rest_framework python3 in the venv is working and importing rest_framework fine: (venv) myname@server:/www/site$ python Python 3.5.2 (default, Nov 17 2016, 17:05:23) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import rest_framework … -
how to check is_staff in post_save() signals
I am working on project ,In which user can register as Doctor or Patient.when user is register as Doctor is_staff is set true ,but when i try to access it in post_Save() method it always return false even though when i take a look on Django site Doctor user are indicated as staff member ,I am not getting how to handle if any one can help me. I also tried to kwargs['is_staff'] but it say there is no attribute like that in User model def update_profile_signal(sender, instance, created, **kwargs): print(kwargs['is_staff']) if created : print(instance.user_type) PateintProfile.objects.create(user=instance) instance.pateintprofile.save() post_save.connect(update_profile_signal,sender=UserProfileInfo) -
Auth-token Getting "DoesNotExist at /api/accounts/register Token matching query does not exist." response despite account registering successfully
I'm creating a Django back-end with token authentication. I am currently running into this issue when registering a user using postman. Despite the response I receive the user-account and token still gets created successfully Response: DoesNotExist at /api/accounts/register Token matching query does not exist. API registration View @api_view(['POST']) def registration_view(request): if request.method == 'POST': serializer = AccountRegistrationSerializer(data=request.data) data = {} if serializer.is_valid(): account = serializer.save() data['response'] = "successfully registered a new user." token = Token.objects.get(user=account).key data['token'] = token else: data = serializer.errors return Response(data) Traceback: Traceback: File "C:\Users\liamr\.virtualenvs\Harryandsam-e8SFW3Fu\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\liamr\.virtualenvs\Harryandsam-e8SFW3Fu\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\liamr\.virtualenvs\Harryandsam-e8SFW3Fu\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\liamr\.virtualenvs\Harryandsam-e8SFW3Fu\lib\site-packages\django\views\decorators\csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "C:\Users\liamr\.virtualenvs\Harryandsam-e8SFW3Fu\lib\site-packages\django\views\generic\base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "C:\Users\liamr\.virtualenvs\Harryandsam-e8SFW3Fu\lib\site-packages\rest_framework\views.py" in dispatch 505. response = self.handle_exception(exc) File "C:\Users\liamr\.virtualenvs\Harryandsam-e8SFW3Fu\lib\site-packages\rest_framework\views.py" in handle_exception 465. self.raise_uncaught_exception(exc) File "C:\Users\liamr\.virtualenvs\Harryandsam-e8SFW3Fu\lib\site-packages\rest_framework\views.py" in raise_uncaught_exception 476. raise exc File "C:\Users\liamr\.virtualenvs\Harryandsam-e8SFW3Fu\lib\site-packages\rest_framework\views.py" in dispatch 502. response = handler(request, *args, **kwargs) File "C:\Users\liamr\.virtualenvs\Harryandsam-e8SFW3Fu\lib\site-packages\rest_framework\decorators.py" in handler 50. return func(*args, **kwargs) File "C:\dev\Harryandsam\harryandsam\accounts\api\views.py" in registration_view 19. token = Token.objects.get(user=account).key File "C:\Users\liamr\.virtualenvs\Harryandsam-e8SFW3Fu\lib\site-packages\django\db\models\manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\liamr\.virtualenvs\Harryandsam-e8SFW3Fu\lib\site-packages\django\db\models\query.py" in get 408. self.model._meta.object_name -
Cannot locate a static file. I get an error that 'STATIC_ROOT' is not set
What I want to do I'm trying to deploy my Django app using AWS (EC2), nginx, and gunicorn. The current goal is to place the static files in the directory /usr/share/nginx/html/static. Problem that is occurring I created /usr/share/nginx/html/static and then ran python manage.py collectstatic command. I had set STATIC_ROOT in settings.py to STATIC_ROOT='/usr/share/nginx/html/static' before, so I thought I could use the collectstatic command to collect static files from within the Django project and place them in /usr/share/nginx/html/static. However, that wasn't the case. Instead I got an error saying django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. Could you please explain why this is so? I have tried some suggested solutions over the internet but the problem still exists. I’d be really appreciated if you could reply to me. error message 'STATIC_ROOT' -
Django - Only some static images not showing up in deployment
So I have my static url set as such under settings: settings.py STATIC_URL = '/static/' if DEBUG or not DEBUG: STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'tabular', 'templates'), os.path.join(BASE_DIR, 'common'), ) Then here is my folder path with the static files I have a webpage with logo.png and step1.png-step4.png. For some odd reason when I'm running in deployment, it correct fetches logo.png, but not step1.png-step4.png. Here is the html code. <div id="wrapper"> <div id="container"> <img style="padding: 1em;" src="{% static 'images/logo.png' %}" /> <form class="form-horizontal" enctype="multipart/form-data" id="data_upload" method="POST" > {% csrf_token %} <div class="input-group mb-3"> <div class="custom-file"> <input accept=".csv" class="custom-file-input" id="file_input" name="file" type="file" /> <label aria-describedby="inputGroupFileAddon02" class="custom-file-label" for="inputGroupFile02" id="submit_label" >Upload CSV</label > </div> <div class="input-group-append"> <button class="input-group-text btn" id="upload_button" type="submit" disabled > Upload </button> </div> </div> <div id="progress_div" class="progress" style="visibility: hidden;"> <div id="progress_bar" class="progress-bar" role="progressbar" style="width: 0%;" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100" ></div> </div> <br /> <div id="spinner" class="d-flex justify-content-center" style="visibility: hidden;" > <div class="spinner-border text-primary" role="status"> <span class="sr-only">Loading...</span> </div> </div> </form> </div> </div> <div class="modal fade" id="my_modal" tabindex="-1" role="dialog" data-target="#my_modal" aria-labelledby="exampleModalLabel" aria-hidden="true" > <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="modal_title">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close" > <span aria-hidden="true">&times;</span> </button> </div> <div id="modal_body" class="modal-body"></div> </div> </div> </div> <div class="modal fade" id="how_to_modal" … -
from: can't read /var/mail/django.utils.version when running django-admin.py
I'm trying to install Django v3.0.6 (or any other v3.x.y) in my macOS. Following are the steps that I've done: installed python3 using homebrew, then ran sudo pip3 install virtualenv, navigating into my target project folder, ran virtualenv venv -p python3. After activating it, ran pip install Django==3.0.6. This resulted in a successful installation of Django 3.0.6. However, when I run django-admin.py startproject myproject I immediately get the following error: from: can't read /var/mail/django.utils.version /usr/local/bin/django-admin.py: line 3: syntax error near unexpected token `(' /usr/local/bin/django-admin.py: line 3: `VERSION = (3, 0, 6, 'final', 0)' Trying to to run this django-admin.py command using the virtualenv is actually my second attempt. I initially started trying with installing Django directly in my machine, not using virtualenv, which also resulted in the same error. My assumption is that happened because the default python version in my machine/OS is 2.7. Any help would be greatly appreciated! -
ModelForm ''Select' object has no attribute 'fields'
I'm using the Django form.selectmultiple field for EntityForm. I'm trying to add CSS classes to form.selectmultiple. This is the code that I wrote. forms.py class Select(forms.SelectMultiple): template_name = "entity/choices/choices.html" def __init__(self, *args, **kwargs): super(Select, self).__init__(*args, **kwargs) for field in self.fields: self.fields[field].widget.attrs["class"] = "no-autoinit" class Media: css = {"all": ("css/base.min.css", "css/choices.min.css",)} js = ("js/choices.min.js",) class EntityForm(forms.ModelForm): class Meta: model = Entity fields = ["main_tag", "tags"] widgets = { "tags": Select(), } I have the following error: AttributeError: 'Select' object has no attribute 'fields' How can I fix the problem? Any help would be appreciated. -
Why isn't my html style only applying to the body even though I am using block content?
So I am attempting to add a style for the body of my page but unfortunately it is applying to my navbar too which is coming from my base.html. What am I doing wrong here that it's applying to my navbar too? I only want it to apply the contents in <body> messages.html {% extends "dating_app/base.html" %} {% load bootstrap4 %} {% load static %} <!DOCTYPE html> <html> <head> </head> <meta name="viewport" content="width=device-width, initial-scale=1"> {% block content %} <style> body { margin: 0 auto; max-width: 800px; padding: 0 20px; } .container { border: 2px solid #dedede; background-color: #f1f1f1; border-radius: 5px; padding: 10px; margin: 10px 0; } .darker { border-color: #ccc; background-color: #ddd; } .container::after { content: ""; clear: both; display: table; } .container img { float: left; max-width: 60px; width: 100%; margin-right: 20px; border-radius: 50%; } .container img.right { float: right; margin-left: 20px; margin-right:0; } .time-right { float: right; color: #aaa; } .time-left { float: left; color: #999; } </style> <body> <a href="{% url 'dating_app:message' other_user.id %}">Start messaging!</a> <h2>Chat Messages</h2> {% for message in messages %} {% if message.sender_id == request.user.id %} <div class="container"> <img src="{{ profile.photo.url }}" alt="Avatar" style="width:100%;"> <p>{{ message.message }}</p> <span class="time-right">{{ message.date }}</span> </div> {% elif … -
Django User Model: Raised exception on delete
Unfortunately, the stack trace given does not give any detail as to the cause of this error or any useful information. When I try to delete a user, in admin or in a method, this exception is raised and I have no idea why. [2020-06-05 03:04:20] ERROR Internal Server Error: /v1/search/events/attending-and-following/ Traceback (most recent call last): File "/home/fendy/Desktop/Collegeapp-Django-development/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/fendy/Desktop/Collegeapp-Django-development/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/fendy/Desktop/Collegeapp-Django-development/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/fendy/Desktop/Collegeapp-Django-development/env/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/fendy/Desktop/Collegeapp-Django-development/env/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/fendy/Desktop/Collegeapp-Django-development/env/lib/python3.6/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/home/fendy/Desktop/Collegeapp-Django-development/env/lib/python3.6/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/home/fendy/Desktop/Collegeapp-Django-development/env/lib/python3.6/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/home/fendy/Desktop/Collegeapp-Django-development/env/lib/python3.6/site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "/home/fendy/Desktop/Collegeapp-Django/search_indexes/views/event_details.py", line 47, in get user.delete() File "/home/fendy/Desktop/Collegeapp-Django-development/env/lib/python3.6/site-packages/django/db/models/base.py", line 937, in delete collector.collect([self], keep_parents=keep_parents) File "/home/fendy/Desktop/Collegeapp-Django-development/env/lib/python3.6/site-packages/django/db/models/deletion.py", line 245, in collect field.remote_field.on_delete(self, field, sub_objs, self.using) TypeError: SET() takes 1 positional argument but 4 were given -
Fair task processing order with Celery+Rabbitmq
I have a Django applications serving multiple users. Each user can submit resource-intensive tasks (minutes to hours) to be executed. I want to execute the tasks based on a fair distribution of the resources. The backend uses Celery and RabbitMQ for task execution. I have looked extensively and haven't been able to find any solution for my particular case (or haven't been able to piece it together.) As far as I can tell, there isn't any build-in features able to do this in Celery and RabbitMQ. Is it possible to have custom code to handle the order of execution of the tasks? This would allow to calculate priorities based on user data and chose which task should be executed next. Related: How can Celery distribute users' tasks in a fair way? -
Columns in Bulma lies horizontally, can we fix the number of column in one row and rest in another?
<section class="section"> <div class="container"> <div class="tile is-ancestor"> '''{% for service in allServices %}''' <div class="tile is-vertical is-parent"> <div class="tile is-child box"> <h1 class="title is-centered">{{service.serviceTitle}} </h1> </div> </div> '''{% endfor %}''' </div> </div> [ if i keep on adding column it lies horizontally no matter how many columns you have* -
Can't retrieve data from mysql to html template in django (PyCharm)
I am hoping someone can help me here; been stuck for a while in this part of learning web development. I am using django in PyCharm community edition. Everything with Apache and MySQL seems to be working well. I am at the stage of making html templates and I am able to log data into MySQL databases. I wanted to retrieve data from a database into a template but it just does not work and I get a warning saying "Unresolved attribute reference '…' for class '…'" when defining a view in PyCharm. These are my files: # views.py from django.shortcuts import render from .models import AirplanePics # AirplanePics is a model def pictures(request): obj = AirplanePics.objects.get(id=1) context = { 'datax': obj, } return render(request, 'pictures.html') In models, I tried a workaround that I read in this forum, but it just recognized 'objects' (in the views.py class) and removed the warning # models.py from django.db import models class AirplanePics(models.Model): author = models.CharField(max_length=30) title = models.CharField(max_length=30) description = models.TextField() def __str__(self): return self.author # models.py (with the workaround) from django.db import models class BaseModel(models.Model): objects = models.Manager() class Meta: abstract = True class AirplanePics(BaseModel): id = models.AutoField(primary_key=True) author = models.CharField(max_length=30) title … -
How lazy are Django QuerySets?
Will the following code Query the database twice? Of course once to begin the for loop, but does it query the database with len()? I ask this because I know the Django count() function queries the database. events = Events.objects.all() for event in events: #First Query print(event.name) length = len(events) #Second Query? -
Confirm simplejwt expire in testcase
I'm just trying to understand djangorestframework-simplejwt expiration and want to know what is returned when the token expires. To explore this a wrote a simple testcase in my django project, but I can't seem to get the expire to occur. views.py import json from http import HTTPStatus from django.http import JsonResponse from rest_framework.decorators import api_view from .models import Visitor @api_view(["POST"]) def visitor_post(request): body_unicode = request.body.decode("utf-8") if not body_unicode.strip(): return JsonResponse({"status": HTTPStatus.BAD_REQUEST}, status=HTTPStatus.BAD_REQUEST) body = json.loads(body_unicode) submitted_datetime = body["submitted_datetime"] visitor = Visitor( representative_name=body["representative_name"], visitor_type=body["visitor_type"], visitor_count=body["visitor_count"], submitted_datetime=submitted_datetime, ) visitor.save() return JsonResponse({"status": HTTPStatus.CREATED}, status=HTTPStatus.CREATED) Currently my testcase is as follows: tests.py import datetime import json from time import sleep from http import HTTPStatus from typing import Optional, Tuple from accounts.models import CustomUser from django.urls import reverse from django.utils import timezone from django.test import override_settings from rest_framework.test import APIClient, APITestCase EXPIRE_WAIT_SECONDS = 5 SIMPLE_JWT_EXPIRE_TEST_SETTINGS = { "ACCESS_TOKEN_LIFETIME": datetime.timedelta(seconds=EXPIRE_WAIT_SECONDS), "REFRESH_TOKEN_LIFETIME": datetime.timedelta(days=14), "ROTATE_REFRESH_TOKENS": True, "BLACKLIST_AFTER_ROTATION": False, "ALGORITHM": "HS256", "SIGNING_KEY": 'kkdkasjf;a', "VERIFYING_KEY": None, "AUTH_HEADER_TYPES": ("JWT",), "USER_ID_FIELD": "id", "USER_ID_CLAIM": "user_id", "AUTH_TOKEN_CLASSES": ("rest_framework_simplejwt.tokens.AccessToken",), "TOKEN_TYPE_CLAIM": "token_type", } class ViewsTestCase(APITestCase): def setUp(self): self.valid_user = CustomUser(last_name="user", first_name="valid", username="validuser", email="validuser@email.com") self.valid_user_password = "mysecretpassword" self.valid_user.set_password(self.valid_user_password) self.valid_user.save() self.apiclient = APIClient() def _get_jwt_token(self, username: Optional[str] = None, password: Optional[str] = None) -> Tuple[str, str]: if not … -
I Have problem for using pip install flask-mysqldb on window 10 64bit , I got an Error
I trying to install MYSQL on window 10 64 bit , I have python3.7.4 version when I tray pip install mysql I got Error MySQLdb/_mysql.c(29): fatal error C1083: Cannot open include file: 'mysql.h': No such file or directory , so I have Python Version: 3.7.4 Operating System: Windows 10 Pip Version: 20.1 Cannot pip install flask-mysqldb Here is a summary of the error i'm getting... C:\Users\Omar Faaruuq>pip install mysql Collecting mysql Downloading mysql-0.0.2.tar.gz (1.9 kB) Collecting mysqlclient Using cached mysqlclient-1.4.6.tar.gz (85 kB) Building wheels for collected packages: mysql, mysqlclient Building wheel for mysql (setup.py) ... done Created wheel for mysql: filename=mysql-0.0.2-py3-none-any.whl size=1252 sha256=fd9a7bdc9cfebc286a66598c32d555b935dfa38a3e1b687096dfa22bf50100d1 Stored in directory: c:\users\omar faaruuq\appdata\local\pip\cache\wheels\f6\60\6d\b1cf0653d003ddb0be2985a4d5f2c6f977d91f0862df094de8 Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'c:\users\omar faaruuq\appdata\local\programs\python\python37-32\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\OMARFA~1\\AppData\\Local\\Temp\\pip-install-m0eys0mm\\mysqlclient\\setup.py'"'"'; __file__='"'"'C:\\Users\\OMARFA~1\\AppData\\Local\\Temp\\pip-install-m0eys0mm\\mysqlclient\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\OMARFA~1\AppData\Local\Temp\pip-wheel-usgog472' cwd: C:\Users\OMARFA~1\AppData\Local\Temp\pip-install-m0eys0mm\mysqlclient\ Complete output (30 lines): running bdist_wheel running build running build_py creating build creating build\lib.win32-3.7 creating build\lib.win32-3.7\MySQLdb copying MySQLdb\__init__.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\_exceptions.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\compat.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\connections.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\converters.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\cursors.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\release.py -> build\lib.win32-3.7\MySQLdb copying MySQLdb\times.py -> build\lib.win32-3.7\MySQLdb creating build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win32-3.7\MySQLdb\constants … -
How can I use Ajax to display if username is already taken in django?
I'm trying to implement some code that will search if a username already exists and then display an error if it does dynamically rather than having to refresh the entire page. I tried implementing some JS and Ajax, but since I'm totally new to JS, it's not working and I'm not sure why. What am I doing wrong? reg.html {% extends "dating_app/base.html" %} {% load bootstrap4 %} {% block content %} {% block javascript %} <script> $("#id_username").change(function () { var username = $(this).val(); $.ajax({ url: '/ajax/check_if_username_exists_view/', data: { 'username': username }, dataType: 'json', success: function (data) { if (data.is_taken) { alert("A user with this username already exists."); } } }); }); </script> {% endblock %} <br> <h1 class="text-center" style="color:#f5387ae6">Register to fall in love today!</h1> <form method="post" style="width:700px;margin:auto" action="{% url 'dating_app:register' %}" enctype="multipart/form-data" class= "form" > <div class="is-valid"> {% bootstrap_form registration_form%} </div> {% csrf_token %} {% for field in bootstrap_form %} <p> {{field.label_tag}} {{field}} {% if field.help_text %} <small style="color:grey;">{{field.help_text}}</small> {% endif %} {% for error in field.errors %} <p style="color: red;">{{error}}"</p> {% endfor %} </p> {% endfor %} <div class="form-check"> <input type="checkbox" id="accept-terms" class="form-check-input"> <label for="accept-terms" class="form-check-label">Accept Terms &amp; Conditions</label> </div> <div> <br> <button type="submit">Register</button> </div> </form> {% endblock content … -
How to Schedule task to run at a specific time
I have a quiz application in django. I want to score the quiz one hour after the deadline. How can I schedule the score_quiz function to run one hour after the deadline for that quiz? -
Installing the correct version of GDAL
My version of Python is [MSC v.1916 32 bit (Intel)] on win32 but I cannot see a release 1916 in - http://www.gisinternals.com/release.php https://www.lfd.uci.edu/~gohlke/pythonlibs/#gdal https://trac.osgeo.org/osgeo4w/ Possibly I am misreading the websites. To be honest I found https://trac.osgeo.org/osgeo4w/ very confusing to navigate. Can anyone give me any guidance? -
Why isn't Django project working within pipenv?
I'm trying to get started with Django, and a tutorial I'm following recommended I use a Python Virtual Envrionment to separate projects/dependencies and I'm trying to use pipenv. These are the steps I've taken so far: Creating the virtual environment Installing Django And then here's me trying to create a django project Furthermore, pip freeze shows absolutely nothing in the virtual env so it's like no packages are being installed even though django installed successfully and the pipfile has: I'm very confused as to why the error message is coming up, I apologize as it's my first time using virtual environments. They seem really cool once you get them working.