Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter annotate When Case with foregin key
i have 2 models: class ServiceRequest(models.Model): post_time = models.DateTimeField(default=timezone.now) service = models.IntegerField(default=102) class RequestSession(models.Model): request = models.ForeignKey(ServiceRequest) post_time = models.DateTimeField(default=timezone.now) If service have value 102, it will have one or more RequestSession. I have queryset get all ServiceRequest : ServiceRequest.objects.all() My question is : How to order_by post_time if service!=102, if service=102 i want order by greatest post_time of requestsession_set? i tried annotate but i dont know how to get greatest post_time in requestsession inside When then My query: queryset.annotate(time_filter=Case( When(service_id=102, then=('requestsession_set__post_time')), default=Value('post_time'), output_field=DateTimeField(), ), ).order_by("-time_filter") -
How do i host django website through webmin/virtualmin in hostinger?
I am trying to host a django website using webmin/virtualmin.I uploaded django file, but can't access the website using domain?How can i do this? -
docker does not installs the updated pipfile
I am using docker in my project. Initially there was following packages in Pipfile [packages] django = "*" djangorestframework = "*" celery = "*" whitenoise = "*" redis = "*" django-celery-beat = "*" flower = "*" django-environ = "*" django-redis = "*" "flake8" = "*" coverage = "*" gunicorn = "*" sentry-sdk = "*" django-storages = {extras = ["boto3"], version = "*"} django-anymail = {extras = ["mailgun"], version = "*"} pillow = "*" "psycopg2-binary" = "*" django-money = "*" django-phonenumber-field = "*" phonenumbers = "*" "argon2-cffi" = "*" jsonfield = "*" future = "*" django-contrib-comments = "*" tzlocal = "*" [dev-packages] werkzeug = "*" "autopep8" = "*" "flake8" = "*" I then build my project and it worked fine. But soon after building an image, i installed following packages in my local environment using pipenv install pylint-django pylint-celery django-debug-toolbar django-extensions --dev Now that i have updated my packages list, I tried to rebuild the image using docker-compose -f local.yml build which i guess did not installed those packages so I am getting issue `ModuleNotFoundError: No module named 'debug_toolbar'. Here is my docker configuration FROM python:3.6-alpine ENV PYTHONUNBUFFERED 1 RUN apk update \ # psycopg2 dependencies && apk add --virtual build-deps … -
Unresolved import models Django + Docker
I have a few simple classes in my Django app that are not loading/importing properly. I know that the code works as I am Dockerizing over an existing app. I am fairly sure this is a similar issue to this but I do not know how to update this to use the Python inside my Docker container. I am following this guide (so all settings/configuration is the same). I have 2 classes: a custom user class and a Company model, and I am trying to add a foreign key on the user that links it to a particular Company. On the other side, I will have a many to many relationships (a company can have multiple users). from core.models import Company VS Code says "unresolved import" when I hover on core.models -
Forbidden (CSRF cookie not set.): /paypal/ | Django
I am having problems with django-paypal, the problem occurs at the moment of receiving the paypal IPN when the payment is successfully completed. Error: Forbidden (CSRF cookie not set.): /paypal/ [15/Sep/2019 22:53:04] "POST /paypal/ HTTP/1.1" 403 2896 Forbidden (CSRF cookie not set.): /paypal/ [15/Sep/2019 22:53:19] "POST /paypal/ HTTP/1.1" 403 2896 Forbidden (CSRF cookie not set.): /paypal/ [15/Sep/2019 22:53:42] "POST /paypal/ HTTP/1.1" 403 2896 Forbidden (CSRF cookie not set.): /paypal/ [15/Sep/2019 22:54:24] "POST /paypal/ HTTP/1.1" 403 2896 Forbidden (CSRF cookie not set.): /paypal/ [15/Sep/2019 22:55:45] "POST /paypal/ HTTP/1.1" 403 2896 I don't know what is happening, I started to investigate the error but I did not achieve much, investigating I put in the file settings.py CSRF_COOKIE_SECURE as True, and even then it did not work, any solution ?. -
Create postgresql command based on DELETE REST call within Django
So I have roughly the following: class exampleSerializer(serializers.ModelSerializer): def delete(self, request, *args, **kwargs): //Custom code The goal is to access the data of the row that the delete function is gonna delete. Based on this information I need to make some extra PostgreSQL commands before the functions finishes. How can I access this data? -
Form HTML, GET method. URL with multiple keywords
I'm building a search page that allows doing a search from 1-4 keywords that through the get method sends to the results page.(eg. for those keywords: one, two tree --> website.com/search/q=one+two+tree) Right now when I add more keywords and press search it sends to the URL using just the keyword in the text input. I tried to create a string joining the keywords with the "+" but sitll doesn't work. The following code is what I have tried. This is a django webapp and in the form.py there is one charfield with an id tag named "add_keyword". The function that doesn't work is send_keywords() <body> <link rel="stylesheet" href="style.css"> <script type="text/javascript"> var keywords_array = [] function getInputValue() { if (keywords_array.length<4){ var ul = document.getElementById("keywords"); var li = document.createElement("li"); var inputVal = document.querySelector("#add_keyword").value; li.appendChild(document.createTextNode(inputVal)); ul.appendChild(li); keywords_array.push(inputVal); } if (keywords_array.length==4){ console.log("You've added the max number of keywords") } } function send_keywords() { query = keywords_array.join("+") window.location.href= window.location.href+"/search/q="+query return query } </script> <h1>Dulcis in Fundo</h1> <h2>Let's coock something, what do you have left?</h2> {% block content %} <form class="" action="/search/" method="GET"> <ul id="keywords"> </ul> {{ form }} <button type="button" onclick="getInputValue();" name="button">add</button> <button type="submit" onclick="send_keywords()">Search</button> </form> {% endblock %} </body> -
Support for partial file downloads using HTTP / REST
I have a client/server architecture in which the client needs to periodically download large files from the server. Let's say the client downloads 9Gb of a 10Gb file and then temporarily loses internet connection. When the client regains connection, I would like the client to be able to download the remaining 1Gb of the file rather than need to re-download everything from scratch. Is there any platform, libraries, frameworks, etc. which handles this? If not, does anyone have any ideas on how to best approach this problem? Server/Client Technologies Server - Python / Django / Django REST Framework Client - Android / iOS / c++ Current Server Code def post(self, request): try: user = request.user file = MyFile.objects.filter(user_id=user) response = FileResponse(open(file.path, 'rb')) return response except Exception as e: return Response({'status': str(e)}, content_type="application/json") -
OperationalError at /admin/budget/expense/add/
When trying to save a new expense on http://localhost:8000/admin/budget/expense/add/ I recieve a OperationalError message saying: no such table: budget_expense I think it may be something relating to how my models.py file is set up: from django.utils.text import slugify # Create your models here. class Project(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique=True, blank=True) budget = models.IntegerField() def save(self, * args, **kwargs): self.slug = slugify(self.name) super(Project, self).save(*args, **kwargs) class Category(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) name = models.CharField(max_length=50) class Expense(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) title = models.CharField(max_length=100) amount = models.DecimalField(max_digits=8, decimal_places=2) category = models.ForeignKey(Category, on_delete=models.CASCADE) For more context this is what the error message looks like: Request Method: POST Request URL: http://localhost:8000/admin/budget/expense/add/ Django Version: 2.2.5 Exception Type: OperationalError Exception Value: no such table: budget_expense Exception Location: C:\Python37\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 383 Python Executable: C:\Python37\python.exe Python Version: 3.7.4 Python Path: ['C:\\Users\\kobby\\Documents\\financio', 'C:\\Python37\\python37.zip', 'C:\\Python37\\DLLs', 'C:\\Python37\\lib', 'C:\\Python37', 'C:\\Python37\\lib\\site-packages'] Server time: Sun, 15 Sep 2019 20:00:54 +0000 I can connect to Django admin just fine and I've been able to add 'projects' however when I want to add 'expenses' that's when the error comes. Any suggestions as to why this may be? -
trying to call Django view on button submit and redirect to the same page (reloaded)
I am trying to call a view that registers players to a tournament on button click, register them in the view, then essentially refresh the page to reflect their new registration. I have here views.py: from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Tournament, TournamentRegistration def index(request): tournaments = Tournament.objects.order_by("-start_time") context = {'tournaments': tournaments} return render(request, 'tournaments/index.html', context) def tournament_detail(request, tourney_id): tournament = Tournament.objects.get(pk=tourney_id) user = request.user player_is_registered = TournamentRegistration.player_is_registered(tourney_id, user.id) print(player_is_registered) if player_is_registered: registered = 'yes' else: registered = 'no' context = {'tournament': tournament, 'player_is_registered': registered} return render(request, 'tournaments/tournament_detail.html', context) def register_for_tournament(request, tourney_id, player_id): registration = TournamentRegistration(tournament=tourney_id, player=player_id) registration.save() return redirect(tournament_detail, tourney_id=tourney_id) tournaments/urls.py: from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<tourney_id>[0-9]+)/$', views.tournament_detail, name='tournament_detail'), url(r'^(?P<tourney_id>[0-9]+)/(?P<player_id>[0-9]+)/$', views.register_for_tournament, name='tournament_registration'), ] main urls.py: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'accounts/', include('accounts.urls')), url(r'accounts/', include('django.contrib.auth.urls')), url(r'^tournaments/', include('tournaments.urls')), url(r'', TemplateView.as_view(template_name='home.html'), name='home'), ] The template for tournament registration: <body> <p>User ID: {{ user.id }}</p> <p>{{ tournament.name }}</p> <p>Start time: {{ tournament.start_time }}</p> <p>Registered: {{ player_is_registered }}</p> <form action="/tournaments/{{tournament.pk}}/{{user.id}}" method="GET"> <button type="submit">Register</button> </form> </body> I came up with this code based on examples I found online. But to my dismay, instead of refreshing and showing the same page with the player registered, … -
Django Registration Form w/ Image
I have a UserProfile Model with an image field, I can upload the image from the admin. Now, I want to implement this image upload in the registration form. views.py class UserRegisterView(FormView): template_name = 'accounts/user_register_form.html' form_class = UserRegisterForm success_url = '/login' def form_valid(self, form): username = form.cleaned_data.get("username") email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") image = form.cleaned_data.get("image") new_user = User.objects.create(username=username, email=email, image=image) new_user.set_password(password) new_user.save() messages.add_message(self.request, messages.INFO, 'Welcome') return super(UserRegisterView, self).form_valid(form) forms.py class UserRegisterForm(forms.Form): username = forms.CharField() email = forms.EmailField() image = forms.FileField() password = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput) def clean_password2(self): ... def clean_image(self): image = self.cleaned_data.get('image') return image user_register_form.html Image : {{ form.image }} What am I missing? Thank you -
How to temporarily disable a token in Django REST Framework
I have created a Django app using REST Framework and created user and token for authentication using the following commands: python manage.py createsuperuser --username Alex --email Alex@example.com python manage.py drf_create_token Alex I can view newly created user (Alex) and its token in Django admin panel and have no problem with authentication but I want to be able to sometimes temporarily disable a token (say for Alex for example) so that he could not authenticate. Is there anyway to disable token? Note: recreating the token is not an option because upon executing python manage.py drf_create_token Alex a completely new token will be generated. -
how to override django files?
I have a function that crops user images but I don't want the model to have 2 fields so I made a function that overrides the original file and I noticed that the function works well on normal files but when I add the function to the view new file is made but at the media directory not even the the specified folder so how can i override files by Django ? the cropping function: import os from PIL import Image def crop(corrd, file ,path,pk): image = Image.open(file) path_1 , fn = os.path.split(path) patient_dir = 'patient_{}'.format(pk) path_ = path_1+patient_dir+fn cropped_image = image.crop(corrd) resized_image = cropped_image.resize((384, 384), Image.ANTIALIAS) resized_image.save(path_) return path_ views.py if form.is_valid(): image = form.save(commit=False) x = float(request.POST.get('x')) y = float(request.POST.get('y')) w = float(request.POST.get('width')) h = float(request.POST.get('height')) print(x) print(y) print(w) print(h) crop((x,y,w+x,y+h),image.pre_analysed,image.pre_analysed.path) image.patient = patient messages.success(request,"Image added successfully!") image.save() forms.py class ImageForm(ModelForm): x = forms.FloatField(widget=forms.HiddenInput()) y = forms.FloatField(widget=forms.HiddenInput()) width = forms.FloatField(widget=forms.HiddenInput()) height = forms.FloatField(widget=forms.HiddenInput()) class Meta: model = UploadedImages fields = ('pre_analysed', 'x', 'y', 'width', 'height', ) models.py class UploadedImages(models.Model): patient = models.ForeignKey(Patient,on_delete=models.CASCADE,related_name='images') pre_analysed = models.ImageField(upload_to = user_directory_path , verbose_name = 'Image') upload_time = models.DateTimeField(default=timezone.now) so what do I need to do here? thanks in advance. -
DRF: token deleting in custom authentication not working
I use djangorestframework and django-rest-auth for authentification api. I want to use a created field of rest_framework.authtoken.models.Token for checking token expiration. So I need to delete an expired token after expires checking, but calling delete() method does not delete token object! settings.py INSTALLED_APPS = [ ... 'rest_framework', 'rest_framework.authtoken', 'rest_auth', ... ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'users.authentication.ExpirationAuth', ), 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ), 'DEFAULT_THROTTLE_RATES': { 'anon': '50/hour', 'user': '100/hour' } } users.authentication.py from rest_framework.authentication import TokenAuthentication, exceptions from django.utils.timezone import get_current_timezone from datetime import datetime, timedelta from config import constants current_timezone = get_current_timezone() class ExpirationAuth(TokenAuthentication): """ Custom authentication with expiration token """ def authenticate_credentials(self, key): model = self.get_model() try: token = model.objects.get(key=key) except model.DoesNotExist: raise exceptions.AuthenticationFailed('Invalid token.') if self.expired(token): token.delete() raise exceptions.AuthenticationFailed('Token has expired.') if not token.user.is_active: raise exceptions.AuthenticationFailed('User inactive or deleted.') return token.user, token @staticmethod def expired(token) -> bool: return token.created < (datetime.now(current_timezone) - timedelta(hours=constants.token_expiration_hours)) If the token has expired I get a message Token has expired., but this token still in the database. -
Django - Post to specific URL using form
I want to post to a specific URL. The url has the scope of deleting a database row. The URL is composed by the address + the pk of the file selected in the form catched from a model. select_file_deletion.html {% extends "index.html" %} {% block content %} <!--Here the number 2 in "/App/delete/2/" needs to be replaced with the pk of the file. The logic is working. --> <form action="/App/delete/{{ myfile.pk }}/" method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <h5>Please select one file at a time from the list below to delete it from the server.</h5> {% for myfile in filename %} <input type="checkbox" name="file_name" value="{{ myfile }}"> <label> <a href="/media/{{ myfile }}">{{ myfile }}</a> <input type="hidden" value="{{ myfile.pk }}" name="pk"> </label> <br> {% endfor %} <br> <button type="submit" class="btn btn-primary">Delete</button> </form> {% endblock %} Project urls.py url(r'^delete/(?P<pk>\d+)/$', FileDeleteView.as_view(), name='APIdelete') views.py class SelectFileDelView(TemplateView): """ This view is used to select a file from the list of files in the server. After the selection, it will send the file to the server. The server will then delete the file. """ template_name = 'select_file_deletion.html' parser_classes = FormParser queryset = FileModel.objects.all() def get_context_data(self, **kwargs): """ This function is used to render … -
How do I pass a value from js to python?
There are buttons for selecting relief and background in The a-frame window. You must pass the values of the JS variable to the python variable to save to the database. How to pass value to django from JS code of button selection? May is variable, "skyEl.setAttribute ('src', '#blank')" assign Python variable var sceneEl = document.querySelector('a-scene'); AFRAME.registerComponent('foo', { init: function () { var skyEl = sceneEl.querySelector('a-sky'); //Changing color using JQuery here $(document).ready(function(){ let color, src,mtl, terrain, text1; $("#text1").click(function(e){ var x = document.getElementById("fname").value; //document.write(x); document.getElementById("output").innerText = x; return false; }); $("#color button").click(function(e){ color = e.currentTarget.className; skyEl.setAttribute('src', '#blank'); skyEl.setAttribute('color', color); {{ background }} = color; }); $("#picture button").click(function(e){ src = e.currentTarget.className; skyEl.removeAttribute('color'); skyEl.setAttribute('src', '#'+src); }); $("#terrain button").click(function(e){ var skob = sceneEl.querySelectorAll('.obj_model'); terrain = e.currentTarget.className; mtl = e.currentTarget.name; for (let index = 0; index <= skob.length; ++index) { //alert(mtl); //skyEl.setAttribute('color', '#1fa9e3'); skob[index].setAttribute('src', '#'+terrain+'-obj'); skob[index].setAttribute('mtl', '#'+mtl); if(terrain=='city'){ skob[index].setAttribute('scale', '30 120 35'); } else { skob[index].setAttribute('scale', '5 10 5') ; } } }); }); } }); sourceURL=pen.js <form method="post"> <div id="left" > <div id="select"> <div id="cssmenu"> {% csrf_token %} <input type="text" placeholder="title" name="title"> <input type="text" placeholder="body" name="body"> <input type="text" placeholder="background" name="background"> <ul> <li class='has-sub'><a href='index.html'><span>Terrain</span></a> <ul> <div id="terrain"> <button onclick="this.disabled=true;" name="city-mtl" value="City" class="city">City</button> <button onclick="this.disabled=true;" name="mars-mtl" … -
Loop through items before rendering pdf and populating table using pdfkit and Django
I'm trying to export all of my users and data related to them in a rendered pdf. I'm struggling to loop over all my users and creating new table rows for each user. As per now the loop loops over all users, but it only populates the table with the data of the last user registered. I do not think I'm able to use Django's conventional way of for looping, at least I cannot figure out how to pass context to the template. views.py def usersExport(request): users = User.objects.all() # populate template tags in generated pdf with data data = dict() for user in users: data['full_name'] = user.get_full_name # getting template, and rendering data template = get_template('backend/users/users_export.html') html = template.render(data) pdf = pdfkit.from_string(html, False) #function for creating file name def create_file_name(): file_name = 'users %s.pdf' % (timezone.now()) return file_name.strip() filename = create_file_name() response = HttpResponse(pdf, content_type = 'application/pdf') response['Content-Disposition'] = 'attachment; filename="' + filename + '"' return response users_export.html <table> <tr class="thead"> <th class="text-left">Name</th> </tr> <tr> <td class="text-left">{{ full_name }}</td> </tr> </table> -
How to add a sub-app in django to INSTALLED_APPS?
I have the structure of my project: project ———— project ———— app ———————— subapp ———— manage.py I added my sub-app to INSTALLED_APPS like that: INSTALLED_APPS = ['app.apps.AppConfig', 'app.subapp.apps.SubapConfig'] But it doesn't works. Django gives me an error message: No module named 'news' and Cannot import 'news'. Check that 'apps.subapp.apps.SubapConfig.name' is correct. -
URL http://localhost:8000/admin/ redirects to wrong page
I'm trying to reach the Django admin page but when I type in http://localhost:8000/admin/ it pops up with my web application instead. For more context I have two url.py's in separate folders. from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('', views.project_list, name='list'), path('<slug:project_slug>/', views.project_detail, name='detail') ] and... from django.urls import path, include urlpatterns = [ path('', include('budget.urls')), path('admin/', admin.site.urls), I'm not sure why http://localhost:8000/admin/ doesn't go to Django's admin page but if anyone has any suggestions that would be very much appreciated. -
URL not found for updateview with polymorphic models and forms in Django
I am trying to display all the models that are related to another model in a modal box when a user clicks on a button. However, the Update view is not working how I want it to work. I am getting a Not Found for the URL pattern related to the class based view (Model Object UpdateView) instead of 200 OK I tried several approaches, but below is the latest one. When I do a print out of the get_queryset (that I have override), I get the objects. I tried to print the context['formset'], but it seems like the code didn't reach that far. I am using django-bootstrap-modal-forms 1.4.2 to display model formsets and I am using django-polymorphic 2.1.2 to deal with polymorphism of the models. forms.py - I create the two forms based on the WebPageObject & LinkObject both inherits from ModelObject (a polymorphic model) I then created a polymorphic modelformset. class ModelWebPageObjectForm(ModelForm): class Meta: model = WebPageObject fields='__all__' class ModelLinkObjectForm(ModelForm): class Meta: model = LinkObject fields = '__all__' Oformset = polymorphic_modelformset_factory(ModelObject,formset_children=( PolymorphicFormSetChild(WebPageObject, form=ModelWebPageObjectForm, fields = '__all__'),), fields='__all__',extra=1) PolymorphicFormSetChild(LinkObject, form=ModelLinkObjectForm, fields = '__all__'), views.py - In this view, I have a used the ModelObject (a polymorphic model) as the … -
Connecting Mysql database in my django project has become a pain as i have tried all the available methods and its not working
Administrator: Windows Powershell Codes: (projectsenv) PS C:\users\amarn\onedrive\desktop\projects\projectsenv> pip install mysqlclient==1.3.12 Collecting mysqlclient==1.3.12 Downloading https://files.pythonhosted.org/packages/6f/86/bad31f1c1bb0cc99e88ca2adb7cb5c71f7a6540c1bb001480513de76a931/mysqlclient-1.3.12.tar.gz (89kB) |████████████████████████████████| 92kB 203kB/s Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: 'c:\users\amarn\onedrive\desktop\projects\projectsenv\scripts\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\Users\amarn\AppData\Local\Temp\pip-install-tz4hbi8_\mysqlclient\setup.py'"'"'; file='"'"'C:\Users\amarn\AppData\Local\Temp\pip-install-tz4hbi8_\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\amarn\AppData\Local\Temp\pip-wheel-9tefdy3z' --python-tag cp37 cwd: C:\Users\amarn\AppData\Local\Temp\pip-install-tz4hbi8_\mysqlclient\ Complete output (25 lines): running bdist_wheel running build running build_py creating build creating build\lib.win32-3.7 copying _mysql_exceptions.py -> build\lib.win32-3.7 creating build\lib.win32-3.7\MySQLdb copying MySQLdb__init__.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 copying MySQLdb\constants\CLIENT.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\ER.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FIELD_TYPE.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\FLAG.py -> build\lib.win32-3.7\MySQLdb\constants copying MySQLdb\constants\REFRESH.py -> build\lib.win32-3.7\MySQLdb\constants running build_ext building 'mysql' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": https://visualstudio.microsoft.com/downloads/ ---------------------------------------- ERROR: Failed building wheel for mysqlclient Running setup.py clean for mysqlclient Failed to build mysqlclient Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error ERROR: Command errored out with exit status 1: command: 'c:\users\amarn\onedrive\desktop\projects\projectsenv\scripts\python.exe' -u … -
Updating highcharts data in django via ajax
I'm running into errors with rendering my highcharts chart via data from the db and can't seem to figure out why Here's the code (document).ready(function() { var options = { chart: { renderTo: 'chart_panel3', type: 'scatter', zoomType: 'xy' }, legend: { enabled: false }, tooltip: { formatter: function () { return "<br/><br/> " + "Date: " + this.x + "<br/><br/> " + "Yr: "+ this.y + "<br/><br/>" + contact_notes3[this.point.index]; }}, xAxis: { gridLineWidth: 0, type: 'datetime', dateTimeLabelFormats: { day: '%m/%d' } }, yAxis: { gridLineWidth: 0, plotLines: [ { value:2019, color: 'grey', width: 0.5}, { value:2018, color: 'grey', width: 0.5}, { value:2017, color: 'grey', width: 0.5}, ] }, plotOptions: { column: { dataLabels: { enabled: true } } }, series: [{}], }; var chartDataUrl3 = "{% url 'chart_data3' pk %}" var contact_notes3 = []; $.getJSON(chartDataUrl3, function(data) { options.xAxis.categories = data['chart_data']['contact_date']; options.series[0].name = 'somename'; options.series[0].data = data['chart_data']['other']; contact_notes3 = data['chart_data']['contact_notes']; var chart = new Highcharts.Chart(options); }); // FYI- this works if I were to uncomment the next set of lines It looked to me that the chart_data3 url endpoint being referenced by chartDataUrl3 may be where the error is coming up, but when I go to the url directly, I get … -
How to generate download link django-oscar
I'm setting up digital shop using Django oscar, it's all well and fine but, I'm trying to figure out how to add a download link. Because of the way django-oscar was set up, each product have AbstractProductAttribute that is related to a ProductClass what I want to do is add a link to thank you page for the download after payment process anyone done this before I need help getting the file attribute of the AbstractProductAttribute thank you. -
DjangoREST vs ExpressJS , which 1 should I choose to build REST API?
I want to build REST API (or GraphQL API) which I want to connect with Angular (2+) to build some nice web application. Which framework should I choose to get started with and why? DjangoREST or ExpressJS ? Which one of them is easier to get connected with front-end frameworks? I know python as well as JavaScript. I also have experience with django as well as some JavaScript front-end frameworks like Angular. So, it wouldn't be that difficult to get started with nodejs or either of them. Which of then is easier and better? -
How to properly link SCSS using PythonAnywhere?
I am currently working on revamping my portfolio, so I decided to switch fully to SCSS instead of CSS. Now even before when I commit from PyCharm I always need to edit it a little bit, to make it work in PythonAnywhere. The explanation: This is the code I use to make it work in PyCharm TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) MEDIA_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' Now to make this work in PythonAnywhere I have to edit above code to this: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['portfolio/templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] MEDIA_ROOT = u'/home/Gromis/portfolio/media' MEDIA_URL = '/media/' STATIC_ROOT = u'/home/Gromis/portfolio/static' STATIC_URL = '/static/' I think that is the issue why I can't properly link SCSS file, is because of the wrong path in settings.py . I get this error now while loading the website: Unable to locate file scss/style.scss while rendering tag 'sass_src' in template project_index.html Of course, the same code works perfectly in PyCharm, so …