Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create questions by fetching from OpenTDB API
I am trying to create a tournament style game and am currently able to create tournaments but no questions. I have started to use forms and really like using them but hit a massive roadblock. I am wondering if I am trying to use multiple models within one view. When I save the tournament which is working, I want to get the difficulty and category from the form and use the OpenTDB API to generate 10 questions and save them. Here is the link to the API. Here are example questions if I chose General Knowledge and Easy... https://opentdb.com/api.php?amount=10&category=9&difficulty=easy. Please help, I have been stuck for days Models.py class Tournament(models.Model): DIFFICULTIES = (('E', ' Easy'), ('M', 'Medium'), ('H', ' Hard')) CATEGORIES = (('9', 'General Knowledge'), ('10', 'Entertainment: Books')) owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='tournaments') name = models.CharField(max_length=255) category = models.CharField(max_length=255, choices=CATEGORIES) difficulty = models.CharField(max_length=255, choices=DIFFICULTIES) start_date = models.DateField(blank=False) end_date = models.DateField(blank=False) class TournamentQuestion(models.Model): tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE, related_name='tournament_questions') text = models.CharField('Tournament question', max_length=255) View.py class TournamentCreateView(CreateView): model = Tournament form_class = AdminTournamentForm template_name = 'users/admins/admin_add_tournament_form.html' success_url = reverse_lazy('admins:admin_dashboard') def get_object(self): return self.request.user.admin def form_valid(self, form): tournament = form.save(commit=False) tournament.owner = self.request.user tournament.save() # THIS IS WHERE I AM REALLY CONFUSED difficulty … -
Django not reading any url pattern other than admin url
I am facing one problem while following along with django(1.9) tutorial from newboston which might seem duplicate but I have tried all scenarios to eliminate this bug but failed. so here it is, I have an app named music in djangoLearn project, but while running this application django is giving this error. It is not reading the any other url pattern other than admin url pattern. Using the URLconf defined in djangoLearn.urls, Django tried these URL patterns, in this order: ^admin/ The current URL, music/, didn't match any of these. djangoLearn\urls.py from django.conf.urls import url,include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^music/', include('music.urls')), ] music\urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$',views.index,name='index') ] music\views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse('<h2>Music section</h2>') I have also included my app's name in installed apps section of settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'music', ] I am using python 2.7 -
How to let user fill in email address in signup_form.html - Django-crispy-forms
Now my signup_form for registering is as attacher picture, user only has username and password, I would like to let user fill in email adress when he is registering, My signup_form.html is as below, is there any way to add a email address in this form without changing views.py of back-end code? {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="row"> <div class="col-md-8 col-sm-10 col-12"> <form method="post" novalidate> {% csrf_token %} <input type="hidden" name="next" value="{{ next }}"> {{ form|crispy }} <button type="submit" class="btn btn-success">Sign up</button> </form> </div> </div> {% endblock %} -
Setup Django2, python3 at apache wiith virtualenv and WSGI
I setup my site.conf in with theses configs: WSGIDaemonProcess linkb1 python-path=/home/test/public/linkb1/public_html:/home/test/vlinkbox/lib/python3.6/site-packages But when i run django i see this error: AttributeError: 'module' object has no attribute 'lru_cache' At my terminal python -V is 3.6.3. I use ubuntu 14.04 How solved this? -
Mysql remote and Cloud database sycn python
I have developed a webapplication using Django Rest framework its an Electronic Health Record System deployed on cloud obut now the customer needs to application to run even when the internet is not available so we decided to deploy it in the local server for the customers hence even when the internet is not available the customer will be available to access it from the local server and the data is moved to cloud db once the internet is up.I need your guidance for the below questionaires. 1) Is there any better way we can do it rather than deploying in local server so that the application works offline also the data load is heavy 2) Incase if i am going with local server deployment is there better way or tools which helps to encrypt the source code and protect it in python 3)Whether i need to create 2 different DB one for local server(there are 4 hospitals which needs to be interconnected) and one for Cloud 4)Whats the best way to sync database offline and online -
'SearchForm' object has no attribute 'get'
I'm trying to create SearchForm with DateField, but form don't see attribute 'get', when I send data method="post". Where is error? forms.py class SearchForm(forms.Form): datee = forms.DateField(input_formats=['%Y-%m-%d'], widget=forms.widgets.DateInput(format="%Y-%m-%d")) views.py def index(request): search_form = search(request) context = {'search_form': search_form} return render(request, 'name/index.html', context) def search(request): if request.method == 'POST': form = SearchForm(data=request.POST) if form.is_valid(): #Do something for examlpe HttpResponseRedirect(reverse("name:second")) else: form = SearchForm() search_form = form return search_form index.html <form method="post" action="{% url 'name:search' %}"> {% csrf_token %} {{ search_form.as_p }} <button name="submit">Search</button> </form> But I'm getting this log and don't understand where is error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/search_result Django Version: 2.0.5 Python Version: 3.6.3 Traceback: File "C:\Users\Александр\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\Александр\AppData\Local\Programs\Python\Python36\lib\site-packages\django\utils\deprecation.py" in __call__ 97. response = self.process_response(request, response) File "C:\Users\Александр\AppData\Local\Programs\Python\Python36\lib\site-packages\django\middleware\clickjacking.py" in process_response 26. if response.get('X-Frame-Options') is not None: Exception Type: AttributeError at /search_result Exception Value: 'SearchForm' object has no attribute 'get' -
Get specific JsonResponse from url in Django
I have set up a JsonResponse method in my views.py: def get_rest_list(request): if request.method == "GET": image_list = Image.objects.order_by('-date') serializer = ImageSerializer(image_list, many=True) return JsonResponse(serializer.data, safe=False) Now if I call that method with "http://localhost:8000/api/" I get a Json from all Image objects that are in the db. How can I get a specific object by its pk when I would do something like this: http://localhost:8000/api/1/ or maybe even: http://localhost:8000/api/445756/ thanks in advance ;) -
How to use scss in django?
How to make work in django index.html with following line? <link href="{{ elixir('css/app.css')}}" rel="stylesheet" type="text/css"> Also I cant find much on howto use sass in django. I have index.html and scss files from laravel, can I make it work in django? Cheers. -
chat server _n heroku
I have this chat server I normaly run with /manage.py run_chat_server I recently deployed my app to heroku and I cant figure out how to run the chat_server. can I get help I h!ve tried with the console in heroku but I just realised that it does not run the manage.py command since it tells me command not found -
In a Queryset use order_by the order that pks/ids are found in an ArrayField
I have a model with an ArrayField: class Item(models.Model): path = ArrayField(models.IntegerField(), blank=True, null=True) The path values, for example: {19,21, 34, 22} I get all Item Objects which ids are in another Item path: qs = Item.filter(id__in=item.path) I need to get the elements, in the order that are in the path(not taking in consideration the values in the Array). Using order_by(path) throws an error: expected string or bytes-like object -
How to create project of python-django in atom
I cannot create a project in Atom for Django Python django-admin is not recognized.enter image description here -
How to run a script shell in django
I am developing a web app using django. I've a script shell that runs python codes for image processing. I want to execute this script shell using my web app so that users can apply image processing just by using a button in the web interface. (for the moment i'm working localy , the django web app and the script shell are in the same folder). I don't know how to do it. can you help me ? thank you in advance. -
How can I add new models and do migrations without restarting the server manually?
For the app I'm building I need to be able to create a new data model in models.py as fast as possible automatically. I created a way to do this by making a seperate python program that opens models.py, edits it, closes it, and does server migrations automatically but there must be a better way. -
Django help for calling rest api from postman
I am very new to python and Django. I have a working python code on my desktop that prints and makes PDFs perfectly. All I want to do is use that code and use Django to allows users to enter a value. My code uses docusign api to call data. I use postman which needs a key and other parameters to use the api. The value entered by my user will determine what data they want/ get I’ve been trying for hours to resolve this issue. What I think I have to do is rewrite my code , put it somewhere then turn it into a view. The view will be sent to template. -
VS Code color coding for comments in Django Templates
Can I write a custom rule to color code the comments in Django Templates? files *.html Example of the tags to trigger on {% comment %} Text in the comment. {% endcomment %} I don't think the Django Snippet plugins do this, but I could be wrong. What I'd like is for that code to show as commented out based on my current theme. Thanks! -
How to convert inmemory file to file object
I am uploading a file and then trying to read it but I am getting TypeError: expected str, bytes or os.PathLike object, not InMemoryUploadedFile my view function is def upload(request,pk): if request.method == 'POST': form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): filehandle=request.FILES['file'] if filehandle: print("File recieved") workbook = xlrd.open_workbook(filehandle) worksheet = workbook.sheet_by_index(0) rows = [] #Some Operartion workbook.close() return HttpResponseRedirect('/products/') -
Google-Oauth2 not registering new user in Django
When I implemented Google Oauth2 in my Django project,at the backend the user column in python social auths is providing admin mail as user and uid as the email of person who signed in. Post that no new user is able to sign in.It states Type Errorenter image description here -
Django queryset order_by absolute value
I have a queryset that has a description attribute and a balance attribute. Currently, when I produce the queryset it is ordered from smallest to largest - - Model.objects.order_by('balance') #output Thing1 -120000 Thing2 -300 Thing3 7000 Thing4 100000 What I would like to order by is decending absolute value such that the result is: #Desired Output Thing1 -120000 Thing4 100000 Thing3 7000 Thing2 -300 I've tried passing various methods inside the order_by() but I think it needs to be an SQL type argument - which I can't figure out. I found this which uses a func expression when annotating. I couldn't get it to work with the order_by and the docs didn't help much. Is there a way to order a queryset in such a way? -
NOT NULL constraint failed: cars_car.owner_id
I was able to render the form onto the html, input data and submit it but i got a NOT NULL contraint failure. Isn't the owner assigned to its respective owners when as i have indicated in my views? i do not know what is wrong here please help! Models class Car(models.Model): owner = models.ForeignKey('auth.User', on_delete=models.CASCADE) name = models.CharField(max_length=100) model = models.CharField(max_length=100) description = models.TextField() image = models.ImageField(upload_to=upload_image_path, null=True, blank=True) created = models.DateField(auto_now_add=True) updated = models.DateField(auto_now_add=False) mileage = models.IntegerField() open_market_value = models.DecimalField(max_digits=12, decimal_places=2) depreciation = models.DecimalField(max_digits=10, decimal_places=2) down_payment = models.DecimalField(max_digits=10, decimal_places=2) road_tax = models.DecimalField(max_digits=8, decimal_places=2) installment = models.DecimalField(max_digits=8, decimal_places=2) objects = models.Manager() def __str__(self): return self.name Views class CarCreate(CreateView): model = Car fields = ['name', 'model', 'description', 'image', 'updated', 'mileage', 'open_market_value', 'depreciation', 'down_payment', 'road_tax', 'installment'] template_name = 'cars/create_car.html' def form_valid(self, form): form.instance.created_by = self.request.user return super().form_valid(form) HTML {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <!-- Default form contact --> <form action="{% url 'cars:create' %}" method="post" enctype="multipart/form-data"> {% csrf_token %} {{form | crispy}} <input type="submit" value="save"> </form> <!-- Default form contact --> {% endblock %} -
upload and read xlsx file in django
I am using xlsx file with django for the first time. I am trying to upload a xlsx file and store its data in my models. But my function is not working this is my views.py def upload(request,pk): if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): filehandle = request.FILES.get('myfile',False) workbook = xlrd.open_workbook(filehandle) worksheet = workbook.sheet_by_index(0) rows = [] for column in range(worksheet.nrows): for row in range(worksheet.nrows): rows.append(worksheet.cell(row, column).value) for i in range(0,len(rows)): if i==0: prodatt = ProductAttribute.objects.get_or_create(name=rows[i],slug=rows[i]) prodatt.save() rows[0]=prodatt.pk elif i>=2: attval = AttributeChoiceValue.objects.get_or_create(name=rows[i],slug=rows[i],attribute=rows[0]) print(attval) attval.save() for i,row in range(worksheet.nrows): if i>1: for j in row: if j>0: a=AttributeChoiceValue.objects.get(name=row[j]).pk d={li[j-1]:a} d1={**d} prod = Product.objects.get_or_create(name=row[0],attributes=d1,product_type=pk) print(prod) prod.save() elif i==0: li=[] for j in row: if j>0: li.append(row[j]) return render(request,'dashboard/list.html') My forms.py have class UploadFileForm(forms.Form): file = forms.FileField() and my template has <form method="post" enctype="multipart/form-data" action="{%url 'dashboard:product-upload' pk=product_type.pk%}"> {% csrf_token %} {{up}} <button type="submit">Upload</button> </form> -
Filtrar utilizando más de tres tablas o clases relacionadas con django
Un saludo comunidad. Me encuentro desarrollando un sistema web con Django y necesito filtrar información donde se involucran varias tablas relacionadas 5 para ser concreto pero estado buscando en varios foros pero sin tener éxito la pregunta es ¿hay como hacer un filtro en el que se incluyan estás tablas o clases. Y como ?. Gracias soy nuevo en este foro. -
Querying two tables using foreign key
I am trying to get all the student's first name and last name from a specific classroom. I can't figure out how to query two table using their foreign keys in Django class Class(models.Model): name = models.CharField(max_length=150) class Student(models.Model): classroom = models.ForeignKey(University, on_delete=models.CASCADE, related_name="students") first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) I want to do the equivalent querying in SQL SELECT first_name, last_name ... FROM Student WHERE classroom = "Class1"... -
override default django admin template in resetting passwords
I'm working in a project with django 2.0 and when resetting password done it didn't render the given template here's my code for url resetting password : from django.urls import path from django .contrib import admin from django.contrib.auth import views as auth_views app_name = 'accounts' urlpatterns = [ path( 'password_reset/done', auth_views.password_reset_done, { "template_name":"accounts/password_reset_done.html" }, name="password_reset_done" ), ] here's a screenshot for what it redirects to : screen -
How should dektop app auth with a server be handled?
I have a simple django website that logged in users can upload files. I am now trying to make a PyQt5 app to make it possible to upload the files from the desktop, after authentication. For now, I'm using requests to https POST with username/password inserted in a login dialog to authenticate the user. If it is successfully, the program saves the session and uses it to send files. The username/password is then saved in a txt file to try to authenticate the user every time he runs the program (this is probably very insecure, but I didn't think of anything better). This system I implemented works well, but as I'm a begginner I would like to know if there is a better, more standard way of doing this. Thanks in advance. -
When using zappa to deploy an aws lambda function, do I create a new django app or run zappa on my existing django app?
I'm trying to create a python deployment package via docker/s3 so I can run my aws lambda function on my django app. However I am unsure whether I am supposed to create a new django app for zappa specifically, or if it is supposed to run on my exisiting app. Just abit confused because every tutorial i'm following says to create a new django app. Apologies if this is a simple question.