Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Account Settings BooleanField
I reviewed most of the posts here related to Django and BooleanField update, but I couldn't find any related to my problem solution. I have a custom user models.py: # Own custom user model class Account(AbstractBaseUser): username = models.CharField(max_length=30, unique=True) guardianSource = models.BooleanField(default=True) bbcSource = models.BooleanField(default=False) independentSource = models.BooleanField(default=False) categoryCoronaVirus = models.BooleanField(default=False) categoryPolitics = models.BooleanField(default=False) categorySport = models.BooleanField(default=False) When I register a user it seems to register in the database all correct values for the checkboxes. The problem is when I want to edit user information I cannot see if a checkbox was checked on registering or not, it displays the checkboxes itself, but they are all empty (False). However, it correctly requests the username and displays it so I can edit it, but all the checkboxes are unchecked. views.py: def account_view(request): if not request.user.is_authenticated: return redirect('login') context = {} if request.POST: form = AccountUpdateForm(request.POST, instance=request.user) if form.is_valid(): form.save() context['success_message'] = "Updated" else: # Display the saved user details from database form = AccountUpdateForm( initial = { 'username':request.user.username, "guardianSource": request.user.guardianSource, "bbcSource": request.user.bbcSource, "independentSource": request.user.independentSource, "categoryCoronaVirus": request.user.categoryCoronaVirus, "categoryPolitics": request.user.categoryPolitics, "categorySport": request.user.categorySport, }) context['account_form'] = form return render(request, 'accounts/account.html', context) account html: {% extends 'base.html' %} {% block content %} <form class="form-signin" … -
Unable to push my django app to heroku due to requirements
So I'm trying to deploy my Django app to heroku (using their tutorial) and I get the following error Terminal info: diaj3@diaj3-TUF-Gaming-FX505DD-FX505DD:~/Desktop/direct_bet$ git push heroku master Counting objects: 9177, done. Delta compression using up to 8 threads. Compressing objects: 100% (5988/5988), done. Writing objects: 100% (9177/9177), 20.59 MiB | 1.29 MiB/s, done. Total 9177 (delta 2148), reused 9177 (delta 2148) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: cp: cannot create regular file '/app/tmp/cache/.heroku/requirements.txt': No such file or directory remote: -----> Installing python-3.6.10 remote: -----> Installing pip remote: -----> Installing SQLite3 remote: Sqlite3 successfully installed. remote: -----> Installing requirements with pip remote: ERROR: Could not find a version that satisfies the requirement apt-clone==0.2.1 (from -r /tmp/build_ca7b1fda063f2c983e5082dbb19235bf/requirements.txt (line 1)) (from versions: none) remote: ERROR: No matching distribution found for apt-clone==0.2.1 (from -r /tmp/build_ca7b1fda063f2c983e5082dbb19235bf/requirements.txt (line 1)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to protected-chamber-65006. remote: To https://git.heroku.com/protected-chamber-65006.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/protected-chamber-65006.git' Here's the Tree info Even tho the requirements file is there, I still get the … -
Double ForeignKey Relation between Models Django
I'm a little confuse here: class MyBirthday(Model): date = models.DateTimeField() invitations_quantity = models.IntegerField() message = models.CharField(max_length=500) user = models.ForeignKey(User) location = models.OneToOneField(Location) class Attendant(Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birthday_id = models.ForeignKey(MyBirthday) The thing is whether or whether not to use the user attribute in MyBirthday model, I mean, is it okay if I just left the Attendant attribute 'birthday_id' reference it? -
in django delete a column in sqlite3 when the time exceeds
In django is there a way to save mobile.no,otp and created_time to DB and let DB remove column when the time created_time is more than 10sec. (like time to live) -
Django 'str' object has no attribute 'username' in forms.py
I'm trying to save the data on to a model. What i have done is created models and forms when i try to submit the form i'm getting an error below 'str' object has no attribute 'username' My model models.py from django.db import models from django.contrib.auth.models import User class Group(models.Model): group_name = models.CharField('Group name', max_length=50) group_admin = models.ForeignKey(User, on_delete=models.CASCADE) is_admin = models.BooleanField(default=False) created_on = models.DateTimeField(auto_now=False, auto_now_add=True) def __str__(self): return self.group_name class GroupMembers(models.Model): group_name = models.ForeignKey(Group,on_delete=models.CASCADE) members = models.ForeignKey(User, on_delete=models.CASCADE) def __unicode__(self): return self.members class Transactions(models.Model): bill_type = models.CharField('Bill type',max_length=200) added_by = models.ForeignKey(User, on_delete=models.CASCADE) added_to = models.ForeignKey(Group, on_delete=models.CASCADE) purchase_date = models.DateField(auto_now=True) share_with = models.CharField('Share among', max_length=250) amount = models.IntegerField(default=0) def __str__(self): return self.bill_type forms.py from django import forms from .models import Transactions, GroupMembers class Bill_CreateForm(forms.ModelForm): def __init__(self, user_list, *args, **kwargs): print("Came here ", user_list) if len(user_list)>0: super(Bill_CreateForm, self).__init__(*args, **kwargs) self.fields['share_with'] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=tuple([(name, name.username.capitalize()) for name in user_list])) #share_with = forms.ModelMultipleChoiceField(queryset=GroupMembers.objects.get(group_header=),widget=forms.CheckboxSelectMultiple) class Meta: model = Transactions fields = ( 'bill_type', 'amount', 'share_with' ) views.py from django.shortcuts import render, redirect from django.contrib.auth.models import User from .models import Transactions, GroupMembers, Group from .forms import Bill_CreateForm from django.http import HttpResponse, HttpResponseRedirect # Create your views here. def add_bills_home(request, id=None): user = User.objects.get(id=id) grp = GroupMembers.objects.get(members=user) … -
Graphene always returning "none" in Json
Im fairly new to GraphQL and Graphene so it's hard for me to grasp whats wrong with my code. I can't even succeed with the simplest of the examples with GraphQL. Here is my code: models.py class Task(models.Model): task_name = models.CharField('Aufgabe', max_length=255) project = models.ForeignKey(Project, on_delete=models.CASCADE) done = models.BooleanField(verbose_name="Erledigt", default=False) def __str__(self): return self.task_name schema.py class Task(models.Model): task_name = models.CharField('Aufgabe', max_length=255) project = models.ForeignKey(Project, on_delete=models.CASCADE) done = models.BooleanField(verbose_name="Erledigt", default=False) def __str__(self): return self.task_name My Query in the same file: class TaskQuery(graphene.ObjectType): all_tasks = graphene.List(TaskType) def resolve_all_tasks(self, info, **kwargs): return Task.objects.all() Another Queryfunction: class Query(graphene.ObjectType): tasks = TaskQuery.all_tasks projects = ProjectQuery.all_projects This is my schema.py int the settings directory: import graphene from todo import schema class Query(schema.Query): pass class Mutation(schema.Mutation): pass schema = graphene.Schema(query=Query, mutation=Mutation) When opening GraphiQL I can see the Query in the docs, but when I try to use this query like so (for example): query { tasks{ id taskName done } } it always returns this: { "data": { "tasks": null } } Although I am pretty sure that I have entries in my Database that should be displayed there. I have checked the beginners Tutorial a view times and I can't even pass the first hurdle. … -
Ngnix in docker container 500 interlal error
I encounter this issue with nginx and docker: I have two containers, one for my django webapp and another for nginx, i want to nginx container get the browser requests and redirect to my django app, but i keep getting 500 internal error 500 error i follow this tutorial but cant make it nginx config file docker-compose -
Using sass with django, sass_tags not found
I am trying to use sass with django. I followed a tutorial and carried out the following steps; i.) i installed the Django Sass libraries pip install libsass django-compressor django-sass-processor ii.) made the necessary changes to my settings.py file: INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.admin', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'crispy_forms', 'classroom', 'sass_processor', ] ... STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'sass_processor.finders.CssFinder', ] SASS_PROCESSOR_ROOT = os.path.join(BASE_DIR, 'static') iii.) and my html {% load static %} [% load sass_tags %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"> <link href="{% sass_src 'second/css/app/quiz_control.scss' %}" rel="stylesheet" type="text/css" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="{% static 'second/js/app/quiz_control.js' %}" defer></script> </head> However, when I run my project i get the error message: Invalid block tag on line 9: 'sass_src'. Did you forget to register or load this tag? -
How Can I send json file by ajax to django?
Can I send .json with data like (login,password from input html) to django who download this file and check login/password? Then I want return results by django to js,jquery. I dont wan use forms-django in form-html and dont want change urls. code html: <form id='login_form' action="" method="POST"> {% csrf_token %} <div id='Login_form'> <p>Login: </p> <input type="text" onblur="CheckEmptyElements();" id="flogin"> <p>Password: </p> <input type="password" onblur="CheckEmptyElements();" id="lpass"> <div id="butt_form"> <button type="button" class="butt_forme" id="button" onclick="CheckBeforeSend();">Enter</button> </div> </div> </form> code js: var LoginInput = document.getElementById('flogin'); if(LoginInput.value.match(/^[a-zA-Z]+['.']+[a-zA-Z]+[0-9]+$/) == null) { if(document.getElementById('Windows').childElementCount > 2) { document.getElementById('Windows').children[0].remove(); } AddPicture("paperJsConn"); } else // <--- Check login/pass in base django { document.getElementById("button").type = "submit"; $.ajax({ type:"POST", url: '', data: { "login": "password": }, success: function(response){ //animation and change site if correct login/pass or reloaded site. } }); } and views.py: def Logget(request): if request.is_ajax and request.method == "POST": //take login from json and check in base by loop //if find check password if: // correct // return .json or message that is correct. else: // return .json or message that is not correct. return render(request, 'index.html') Someone help please? -
Django Template not rendering {{ }}
I'm not sure where I've gone wrong, but my template is not rendering. I believe I have set all the correct code in the following Python files, but I do not see it rendering. I am using postgresql if that matters: urls.py: from django.contrib import admin from django.urls import path from django.conf import settings from django.conf.urls.static import static import jobs.views urlpatterns = [ path('admin/', admin.site.urls), path('', jobs.views.home, name='home') ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py: INSTALLED_APPS = [ 'blog.apps.BlogConfig', 'jobs.apps.JobsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] views.py from django.shortcuts import render from .models import Job def home(request): jobs = Job.objects return render(request, 'jobs/home.html', {'jobs': jobs}) models.py: from django.db import models class Job(models.Model): image = models.ImageField(upload_to = 'images/') summary = models.CharField(max_length = 200) jobs/templates/jobs/home.html: <div class="album py-5 bg-light"> <div class="container"> <div class="row"> {% for i in jobs.all %} <div class="col-md-4"> <div class="card mb-4 shadow-sm"> <img src="" alt=""> <div class="card-body"> <p class="card-text">{{ jobs.summary }}test</p> </div> </div> </div> {% endfor %} </div> </div> </div> -
Django: delete object with a button
In my website in the user page I've got a list of all the items he added to the database. Next to the items there's a delete button. I'd like the user to be able to delete that item through the button.Thanks a lot! models.py class Info(models.Model): utente = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=1) band = models.CharField(max_length=200) disco = models.CharField(max_length=200) etichetta_p = models.CharField(max_length=200) etichetta_d = models.CharField(max_length=200) matrice = models.CharField(max_length=200) anno = models.PositiveIntegerField(default=0) cover = models.ImageField(upload_to='images/', blank=True) view.py (I'm not sure about this part) def DeleteInfo(request, id=None): instance = get_object_or_404(Info, id=id) instance.delete() return redirect ('search:user') urls.py path('<int:id>/delete', views.DeleteInfo, name='delete'), html template: {% if object_list %} {% for o in object_list %} <div class="container_band"> <div class=album_band> <!-- insert an image --> {%if o.cover%} <img src= "{{o.cover.url}}" width="100%"> {%endif%} </div> <div class="info_band"> <!-- insert table info --> <table> <tr><th><h3>{{o.band}}</h3></th></tr> <tr><td> Anno: </td><td> {{o.anno}} </td></tr> <tr><td> Disco: </td><td> {{o.disco}} </td></tr> <tr><td> Etichetta: </td><td> {{o.etichetta_d}} </td></tr> <tr><td> Matrice: </td><td> {{o.matrice}} </td></tr> </table> </div> <div class="mod"> <table> <tr><td><button> Update </button></td></tr> <tr><td><button> Delete </button></td></tr> </table> </div> </div> {% endfor %} {%endif%} </div> -
Question objects need to have a primary key value before you can access their tags
i am trying to save both FK data as well as tags into same model. FK is the user. user has to submit the question and tags like stack overflow. but i am not able to save both of them. it looks some issue at my views. Can you please help. ValueError at /qanda/askquestion/ Question objects need to have a primary key value before you can access their tags. Request Method: POST Request URL: http://127.0.0.1:8000/qanda/askquestion/ Django Version: 2.2.4 Exception Type: ValueError Exception Value: Question objects need to have a primary key value before you can access their tags. Exception Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/taggit/managers.py in get, line 424 Python Executable: /Library/Frameworks/Python.framework/Versions/3.7/bin/python3.7 Python Version: 3.7.4 Python Path: ['/Users/SRIRAMAPADMAPRABHA/Desktop/IampythonDEV/iampython', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/Users/SRIRAMAPADMAPRABHA/Library/Python/3.7/lib/python/site-packages', '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages'] Models.py class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) question_number = models.AutoField(primary_key=True) question_category=models.ForeignKey(Question_Category,related_name='questioncategory',on_delete=models.CASCADE) question_title=models.CharField(max_length=250) question_slug = models.SlugField(unique=True, max_length=250) question_description=RichTextField() question_tags = TaggableManager() question_posted_at=models.DateTimeField(default=datetime.now,blank=True) question_status= models.IntegerField(choices=STATUS, default=1) question_updated_on= models.DateTimeField(auto_now= True) def __str__(self): return self.question_title views.py @login_required def createQuestion(request): if request.method == 'POST': form = QuestionAskForm(request.POST) if form.is_valid(): new_question=form.save(commit=False) question_title = request.POST['question_title'] new_question.slug = slugify(new_question.question_title) new_question=request.user new_question.save() form.save_m2m() messages.success(request,'You question is succesfully submitted to the forum') return redirect('feed') else: form = QuestionAskForm() return render(request,'qanda/askyourquestion.html',{'form':form}) I want to submit both foreign key and as well as … -
Django static files are not loading with NGINX
Im trying to publish my first Django App on production Server with NGINX. project --app1 --app2 --config settings.py wsgi.py urls.py --venv manage.py nginx configuration server { listen 80; server_name my_IP_adress; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/websites/testAPP; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } In my settings I have the folow code BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ROOT_DIR = environ.Path(__file__) STATIC_URL = '/static/' STATIC_ROOT = str(ROOT_DIR('statics')) STATICFILES_DIRS = [ str(BASE_DIR.path('static')), ] STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] an in urls.py I added ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) But, whe I run collectstatoc on production Server, I get this Error: settings.py", line 24, in <module> str(BASE_DIR.path('static')), AttributeError: 'str' object has no attribute 'path' How can I fix it? -
Reading Pandas dataframe into postgresSQL with Django
Based on this question Saving a Pandas DataFrame to a Django Model I'm trying to add data from excel to my Model. So my model looks like this: class Company(models.Model): KIND = ( (0, "Corporate"), (1, "Start Up"), ) name = models.CharField(verbose_name="full company", max_length=50) address = models.CharField(max_length=100) kind = models.IntegerField(default=0) My excel that is loaded into dataframe looks like this(df): name address kind id 1 Ubisoft Dowtown 0 2 Exxon Tuas Link 1 Now I followed the suggestion in that question and ended up creating the following code in my views.py: from django.shortcuts import render from django.shortcuts import redirect from sqlalchemy import create_engine # Create your views here. from django.http import HttpResponse from django.conf import settings import pandas as pd from importer.models import Company def importer(request): df=pd.read_excel("datafile.xlsx") df.columns=["id", "name", "address", "kind"] df.set_index("id", inplace=True) print(df.dtypes) user = settings.DATABASES['default']['USER'] password = settings.DATABASES['default']['PASSWORD'] database_name = settings.DATABASES['default']['NAME'] database_url = 'postgresql://{user}:{password}@localhost:5433/{database_name}'.format( user=user, password=password, database_name=database_name, ) engine = create_engine(database_url, echo=False) df.to_sql(Company, con=engine, if_exists='append') So it seems that it loads dataframe correctly but then I get error when it is trying to append data to the database in postgresSQL, because I get the following error when I access route corresponding to importer view: Traceback (most recent call … -
Nginx upstream server values when serving an API using docker-compose and kubernetes
I'm trying to use docker-compose and kubernetes as two different solutions to setup a Django API served by Gunicorn (as the web server) and Nginx (as the reverse proxy). Here are the key files: default.tmpl (nginx) - this is converted to default.conf when the environment variable is filled in: upstream api { server ${UPSTREAM_SERVER}; } server { listen 80; location / { proxy_pass http://api; } location /staticfiles { alias /app/static/; } } docker-compose.yaml: version: '3' services: api-gunicorn: build: ./api command: gunicorn --bind=0.0.0.0:8000 api.wsgi:application volumes: - ./api:/app api-proxy: build: ./api-proxy command: /bin/bash -c "envsubst < /etc/nginx/conf.d/default.tmpl > /etc/nginx/conf.d/default.conf && exec nginx -g 'daemon off;'" environment: - UPSTREAM_SERVER=api-gunicorn:8000 ports: - 80:80 volumes: - ./api/static:/app/static depends_on: - api-gunicorn api-deployment.yaml (kubernetes): apiVersion: apps/v1 kind: Deployment metadata: name: release-name-myapp-api-proxy spec: replicas: 1 selector: matchLabels: app.kubernetes.io/name: myapp-api-proxy template: metadata: labels: app.kubernetes.io/name: myapp-api-proxy spec: containers: - name: myapp-api-gunicorn image: "helm-django_api-gunicorn:latest" imagePullPolicy: Never command: - "/bin/bash" args: - "-c" - "gunicorn --bind=0.0.0.0:8000 api.wsgi:application" - name: myapp-api-proxy image: "helm-django_api-proxy:latest" imagePullPolicy: Never command: - "/bin/bash" args: - "-c" - "envsubst < /etc/nginx/conf.d/default.tmpl > /etc/nginx/conf.d/default.conf && exec nginx -g 'daemon off;'" env: - name: UPSTREAM_SERVER value: 127.0.0.1:8000 volumeMounts: - mountPath: /app/static name: api-static-assets-on-host-mount volumes: - name: api-static-assets-on-host-mount hostPath: path: /Users/jonathan.metz/repos/personal/code-demos/kubernetes-demo/helm-django/api/static My … -
from django.allauth.account.adapter import DefaultAccountAdapter ModuleNotFoundError: No module named 'django.allauth'
I have installed django-allauth with docker-compose exec web pipenv install django-allauth, but I recieve an erro from django.allauth.account.adapter import DefaultAccountAdapter ModuleNotFoundError: No module named 'django.allauth', when I use docker-compose exec web python manage.py makemigrations. Thaks for your help :) -
Django dynamic change of LANGUAGE_CODE to use 1 template and 3 translated model fields
I want to use one single template to be displayed in 3 different languages depending on the LANGUAGE_CODE, so I would like to alter the value of LANGUAGE_CODE value and selecting the language from a dropdown menu in my template. My model contains translated fields in 3 languages class Recipe(AuditBaseModel): recipe_id = models.AutoField(primary_key=True) recipe_code = models.CharField(max_length=30, null=False, blank=False) recipe_name = models.TextField(verbose_name=_('recipe_name'), blank=True, null=True) recipe_name_eng = models.TextField(blank=True, null=True) recipe_name_nor = models.TextField(blank=True, null=True) My template is able to show each field depending on the LANGUAGE_CODE {% get_current_language as LANGUAGE_CODE %} {% if LANGUAGE_CODE == 'en-gb' %}<h2>{{ recipe_form.recipe_name_eng.value }}</h2> {% elif LANGUAGE_CODE == 'nb' %}<h2>{{ recipe_form.recipe_name_nor.value }}</h2> {% elif LANGUAGE_CODE == 'es' %}<h2>{{ recipe_form.recipe_name.value }}</h2> {% endif %} Also, in my template, I have a dropdown menu for language selection <li><a href="">Language</a> <ul class="sub-menu"> <li><a href="">English</a></li> <li><a href="">Norsk</a></li> <li><a href="">Espanol</a></li> </ul> </li> How can I dynamically alter the value of LANGUAGE_CODE in my settings.py when the user selects a specific language from the template menu? Any better idea without using i18n? Many thanks in advance -
ERROR: MySQL_python-1.2.5-cp27-none-win_amd64.whl is not a supported wheel on this platform
So i am setting up an old project its python2 and django1 where i'm stuck with installtion of requirement.txt This is the main error i'm getting while installing Building wheel for MySQL-python (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/rehman/projects/comparedjs/bin/python2 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-KyvPG6/MySQL-python/setup.py'"'"'; __file__='"'"'/tmp/pip-install-KyvPG6/MySQL-python/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 /tmp/pip-wheel-jCT7NK cwd: /tmp/pip-install-KyvPG6/MySQL-python/ Complete output (38 lines): running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-2.7 copying _mysql_exceptions.py -> build/lib.linux-x86_64-2.7 creating build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-2.7/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-2.7/MySQLdb creating build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/REFRESH.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-2.7/MySQLdb/constants running build_ext building '_mysql' extension creating build/temp.linux-x86_64-2.7 x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fdebug-prefix-map=/build/python2.7-2.7.16=. -fstack-protector-strong -Wformat -Werror=format-security -fPIC -Dversion_info=(1,2,5,'final',1) -D__version__=1.2.5 -I/usr/include/mariadb -I/usr/include/mariadb/mysql -I/usr/include/python2.7 -c _mysql.c -o build/temp.linux-x86_64-2.7/_mysql.o In file included from _mysql.c:44: /usr/include/mariadb/my_config.h:3:2: warning: #warning This file should not be included by clients, include only <mysql.h> [-Wcpp] #warning This file should not be included by … -
is it ok to use formview instead of updateview, createview in Django?
so I'm new here in django and have already get the point of some generic views but it really gives me a hard time to understand the UpdateView, CreateView and DeleteView all information that I search still not giving me a point on how to use them. So I have a form registration which have username and password but they are in different table or model to save; you may take a look on the forms.py, And trying UpdateView its giving me only an error to my project. So as I found in some forums, i can't use UpdateView to a foreign key table for its looking only a primary key So instead of using them I use FormView replacing by the 3 generic view for now. Is it ok to use the FormView as an option aside the 3 generic view? Here is my source code. forms.py: from django import forms class UserCredentialForm(forms.Form): username = forms.CharField(label = 'Email', widget = forms.TextInput( attrs = { 'id': 'id_login_username', 'class': 'form-control', 'autocomplete': 'off', } ), required = False) password = forms.CharField(label = 'Password', widget = forms.PasswordInput( attrs = { 'id': 'id_login_password', 'class': 'form-control', } ), required = False) class UserInfoForm(forms.Form): year = … -
do i need to learn all functions of programming language? [duplicate]
I am new to programming, i know basics of programming. I also write some code in python, php and javascript. Every programming language has hundreds of builtin functions. For example, every programming language has different functions of string, array, int and file I/O etc. Plus framework functions like django, laravel and codeiginter etc. Do i need to learn all builtin functions? for example if i learn php do i need to learn all functions of php plus laravel/codeiginter or if i learn asp.net do i need to learn all functions of c# and asp.net? i don't think it is possible, because there are hundreds of functions in programming language, functions return types and functions parameters? -
Order Union by created_at
I have a graphene.Union of two models and i'm tying to order the response by created_at field, witch is a matching field for both models. Is there of doing that? Schema.py class PostUnion(graphene.Union): class Meta: types = (PostType, Post2Type) @classmethod def resolve_type(cls, instance, info): # This function tells Graphene what Graphene type the instance is if isinstance(instance, Post): return PostType if isinstance(instance, Post2): return Post2Type return PostUnion.resolve_type(instance, info, search) class Query(graphene.ObjectType): all_posts = graphene.List(PostUnion, search=graphene.String(), limit=graphene.Int()) def resolve_all_posts(self, info, search=None, limit=None): if search: filter = ( Q(id__icontains=search) | Q(title__icontains=search) ) return (list(Post.objects.filter(filter)) + list(Post2.objects.filter(filter)))[:limit] return (list(Post.objects.all()) + list(Post2.objects.all()))[:limit] { allPosts(Order: "created_at") { ... on PostType { id title createdAt } ... on Post2Type { id title createdAt } } } -
SMTPSenderRefused (530, b'5.7.0 Authentication Required)
I make a website with django and im having some troubles whit the reset password feature in deployment with heroku (works fine locally), when i try to use it, an error pops up: SMTPSenderRefused at /password-reset/ (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError a68sm8842573qkd.10 - gsmtp', 'webmaster@localhost') Request Method: POST Request URL: https://mytobiapp.herokuapp.com/password-reset/ Django Version: 3.0.4 Exception Type: SMTPSenderRefused Exception Value: (530, b'5.7.0 Authentication Required. Learn more at\n5.7.0 https://support.google.com/mail/?p=WantAuthError a68sm8842573qkd.10 - gsmtp', 'webmaster@localhost') Exception Location: /app/.heroku/python/lib/python3.6/smtplib.py in sendmail, line 867 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.10 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] settings.py EMAIL_BACKEND="django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST="smtp.gmail.com" EMAIL_PORT=587 EMAIL_USE_TLS= True EMAIL_HOST_USER = os.environ.get("GMAIL") EMAIL_HOST_PASSWORD = os.environ.get("CONTRASEÑA_GMAIL") I already tried to allow acces to less secure apps and use the displayunlockcaptcha feature of google, but nothing seems to work. Any help will be apreciated -
setting django project for production / development enviroment
I am writing a Django project that it needs to be divided as production/development, but however my project looks like this, how can I organize in order to execute python manage.py runserver for dev or prod. . ├── apps │ ├── account │ │ ├── migrations │ │ │ └── __pycache__ │ │ └── __pycache__ │ ├── course │ │ ├── migrations │ │ └── __pycache__ │ ├── quizgame │ │ ├── migrations │ │ │ └── __pycache__ │ │ └── __pycache__ │ └── site │ └── __pycache__ └── app └── __pycache__ 16 directories -
how do i fix this warning?
i wanted to create a simple web aplication using django, and when i run through the terminal the command: django-admin startproject my site and i get the error ''django-admin'' is not recognized as an internal or external command, operable program or batch file. i have tried running cmd as administrator but at the end the same result the problem i guess is this warning: WARNING: The script sqlformat.exe is installed in 'C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\Scripts' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location. can anyone help me how to find a solution p.s i'm very new to programming -
GeoDjango maps on Django forms
I want to have a GeoDjango LeafLet map on my form. On another page I succesfully implemented this, but I do struggle on my forms (CreateView and UpdateView). I do get this errorin my browser console: Uncaught ReferenceError: L is not defined at loadmap (new:109) forms.py from leaflet.forms.fields import PointField from leaflet.forms.widgets import LeafletWidget from django.contrib.gis import forms class TourStepForm(forms.ModelForm): required_css_class = 'required' place = forms.PointField( widget=LeafletWidget(attrs=LEAFLET_WIDGET_ATTRS)) class Meta(): model = Toursteps exclude = ('tour',) views.py class CreateTourStepView(LoginRequiredMixin,CreateView): login_url = '/login/' redirect_field_name = 'tour_admin/tour_list.html' success_url = '/' form_class = TourStepForm model = Toursteps template_name = 'tour_admin/toursteps_form.html' def get_context_data(self, **kwargs): context = super(CreateTourStepView, self).get_context_data(**kwargs) return context def get(self, request, *args, **kwargs): self.tour_id = get_object_or_404(Tour, pk=kwargs['tour_id']) return super(CreateTourStepView, self).get(request, *args, **kwargs) def form_valid(self, form): if form.is_valid(): self.tour_id = self.kwargs.get('tour_id') form.instance.tour_id = self.tour_id form.instance.save() return HttpResponseRedirect(self.get_success_url()) def get_success_url(self): return reverse('tour_detail', kwargs={'pk':self.tour_id}) steps.html {% extends 'tour_admin/admin_base.html' %} {% load crispy_forms_tags %} {% load leaflet_tags %} {% leaflet_css plugins="forms" %} {% leaflet_js plugins="forms" %} {% block content %} {% if user.is_authenticated %} <div class=""> <h1>Step:</h1> <form enctype="multipart/form-data" class="tour-form" method="POST"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="save btn btn-default">Save</button> </form> </div> {% else %} <h1>Not authorised!</h1> {% endif %} {% endblock %}