Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Django Black Not Installing Properly
I received an error after installing Django Black. I ran "pipenv install black --pre". Then when I ran manage.py runserver, I received the error below. Note that I am running Windows 10. from custom_storages import MediaStorage File "C:\Users\dgold2\Documents\py\ibankai\src\custom_storages.py", line 2, in <module> from storages.backends.s3boto3 import S3Boto3Storage File "C:\Users\dgold2\Documents\py\ibankai\src\.venv\lib\site-packages\storages\backends\s3boto3.py", line 18, in <module> from django.utils.six.moves.urllib import parse as urlparse ModuleNotFoundError: No module named 'django.utils.six' -
Invalid URL. Django
I created search form: <form action="{% url 'search_results' %}" method="get"> <div class="row"> <div class="col-lg-8 col-md-6 col-xs-12"> <input name="q" type="text" placeholder="Search..." class="form-control"> </div> <div class="col-lg-3 col-md-6 col-xs-12"> <select name="q2" class="form-control" id="exampleFormControlSelect1"> <option>All locations</option> <option>Москва</option> <option>Петербург</option> <option>Казань</option> </select> </div> <div class="col-lg-1 col-md-6 col-xs-12"> <!-- <button> Search </button> --> <button class="btn btn-primary">Primary</button> </div> </div> </form> When I input "c++" I go to http://127.0.0.1:8001/search/?q=c%2B%2B&q2=%D0%9C%D0%BE%D1%81%D0%BA%D0%B2%D0%B0 (Result is OK, but '+' is interpreted as %2B) When I click pagination "next" I receive http://127.0.0.1:8001/search/?vacancy=2&q=c++&q2=%D0%9C%D0%BE%D1%81%D0%BA%D0%B2%D0%B0 (ERROR Page not found) I need http://127.0.0.1:8001/search/?vacancy=2&q=c%2B%2B&q2=%D0%9C%D0%BE%D1%81%D0%BA%D0%B2%D0%B0 How can I fix this (convert '+' to '%2B')? vacancy_list.html {% extends 'vacancy_list/base.html' %} {% block content %} <div class="container " style="margin:20px;"> <!-- wrapper for all containers --> <div class="container" style="margin-top: 40px; font-size: 2rem;"> <form action="{% url 'search_results' %}" method="get"> <div class="row"> <div class="col-lg-8 col-md-6 col-xs-12"> <input name="q" type="text" placeholder="Search..." class="form-control"> </div> <div class="col-lg-3 col-md-6 col-xs-12"> <select name="q2" class="form-control" id="exampleFormControlSelect1"> <option>All locations</option> <option>Москва</option> <option>Петербург</option> <option>Казань</option> </select> </div> <div class="col-lg-1 col-md-6 col-xs-12"> <!-- <button> Search </button> --> <button class="btn btn-primary">Primary</button> </div> </div> </form> </div> {% for vacancy in vacancies %} <div class="card"> <div class="card-header"> <div class="row"> <div class="col-md-8"> <h1><a href="{% url 'vacancy_detail' pk=vacancy.pk %}">{{vacancy.title}}</a></h1> </div> <div class="col-md-4 text-right"> <p> {{ vacancy.salary}} </p> </div> </div> </div> <div class="card-body" … -
Django CMS CSS trouble?
Im trying to style a plugin in my Django-CMS project ( django 1.11, CMS 3.6.0 ). Im trying to add my class to my plugin html, like this : <div class="question"> <h1 class="question-title">{{ instance.poll.question }}</h1> <form action="{% url 'polls:vote' instance.poll.id %}" method="post"> {% csrf_token %} <div class="form-group"> {% for choice in instance.poll.choice_set.all %} <div class="radio"> <label> <input type="radio" name="choice" value="{{ choice.id }}"> {{ choice.choice_text }} </label> </div> {% endfor %} </div> <input type="submit" value="Vote" /> </form> </div> Then I go into my css, and try to apply some styles to the plugin, but nothing happens. When I inspect my div which should have a class of "question" in the browser, there is no class even though I specified it in my html. Why is that ? When I do something like : body { width: 1060px; margin: 10px auto; } It applies the styles correctly. Anybody knows what is happening here ? Where are my custom classes from the html ? I was trying to find a guide on Django-CMS and styling, but Im not having much luck. Thank you guys ! -
Passing data from external python script in django to swift
Trying to create a swift request where an external python script is run in Django and returns data to the user. I just cant wrap my head around on what best practices there are or on how to do this. Any help would be appreciated. Python script returns print(output) Djano views.py def post(self, request, *args, **kwargs): self.create(request, *args, **kwargs) inp = request.FILES.get('image').name out = run([sys.executable,'//Users//macbookpro//TestAPI//venv//Test_Script.py',inp],shell=False,stdout=PIPE, text= True) print(out.stdout) return Response ({"output": str(out)}) Swift to: REST_UPLOAD_API_URL, headers: headers, encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): upload.responseJSON { response in debugPrint(response) print(stdout) What would be the best way to pass data from the Python script and back to the user? Do i need to create a JSON response in Django and afterwards Decode it in Swift? If so, how would that work? If not, then how can you decode the "stdout" response in Swift which I'm currently receiving. Results so far: print(out.stdout) gives me the desired text response within Django DebugPrint(response) = Returns desires text --> stdout='MyDesiredText\n')"; print(stdout) in Swift gives me = 0x000000010a45d1a8 -
Django file not uploading: ValueError at / The 'image' attribute has no file associated with it
I created a form with django forms. I implemendted on html page. Everything is ok but my image not uploaded on database. I was trying to find issue. I tried print(request.FILES) It returned <MultiValueDict: {}> I understood my uploaded image didn't upload correctly im my database. Though form was submitted and when I tryied to query from product it will get error ValueError at / The 'image' attribute has no file associated with it. this is my traceback Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2.5 Python Version: 3.7.3 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users.apps.UsersConfig', 'product.apps.ProductConfig'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /home/asad/PycharmProjects/eShop/templates/base.html, error at line 8 The 'image' attribute has no file associated with it. 1 : {% load staticfiles %} 2 : <!DOCTYPE html> 3 : <html lang="en"> 4 : <head> 5 : <meta charset="UTF-8"> 6 : <title>{% block title %}{% endblock %}</title> 7 : <!-- Latest compiled and minified CSS --> 8 : <link rel="stylesheet" href="https://maxcd n.bootstrapcdn.com/ bootstrap/4.3.1/css/bootstrap.min.css"> 9 : 10 : 11 : </head> 12 : <body> 13 : 14 : <div class="container"> 15 : <div class="row"> 16 : <div class="col-md-4"> 17 : <a … -
How to save foreign from html form (select)?
I can not save the appropriate value for ForeignKey from the form. The value of ForeignKey is always written to the database, with id = 1. in html form the values from my model, which is in the database, are output to the select. But when sending data from the form, the values of the fields for which the type of foregonekey are written to the database all the time by id = 1 models.py: class Sportsman(models.Model): first_name = models.CharField(max_length=64, blank=True, null=True, default=None, verbose_name='Имя') last_name = models.CharField(max_length=64, blank=True, null=True, default=None, verbose_name='Фамилия') gender = models.ForeignKey(Gender, on_delete=models.CASCADE, null=True, blank=True, default=True, verbose_name='Пол') tournament = models.ForeignKey(Tournament, null=True, blank=True, default=True, on_delete=models.CASCADE, verbose_name='Турнир') def __str__(self): return "Спортсмен(ка): %s %s, почта: %s" % (self.first_name, self.last_name, self.email) class Meta: verbose_name = 'Спортсмен' verbose_name_plural = 'Спортсмены' def save(self, *args, **kwargs): super(Sportsman, self).save(*args, **kwargs) forms.py: class SportsmenForm(forms.ModelForm): class Meta: model = Sportsman exclude = ['created', 'updated'] views.py: def sportsman(request): documents = Document.objects.filter(is_active=True) form = SportsmenForm(request.POST or None) if request.method == "POST" and form.is_valid(): print(request.POST) print(form.cleaned_data) print(form.cleaned_data['email']) form.save() new_form = form.save() return render(request, 'sportsman/sportsman.html', locals()) <QueryDict: {'csrfmiddlewaretoken': ['BzBeiKE82LDcd3tmdzZGSmpOWQatc52SSO7ScEOm7eCVdXsHQWxerSzTZa6KC5xq'], 'first_name': ['test_name'], 'last_name': ['test_name'], '<select name=': ['3']} >