Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get many to many fields changes in a post save in Django 1.11
So, I have a post_save signal in my code to save logs of changes in models, but the changes in many to many fields aren't applied at the point post_save is triggered, so changes in m2m fields aren't saved in my logs. My code (you can pretty much ignore the code inside the method): def save_log(sender, instance, created, raw, update_fields, **kwargs): if ( not hasattr(sender, '_meta') or sender._meta.label not in settings.MODELS_TO_BE_LOGGED ): return sensitive_fields = ['password', ] user = get_user() # This creates the log with a json describing the changes if created: # This method creates a log instance.save_addition(user, '') else: changed_field_labels = {} original_dict = instance.original_dict actual_dict = instance.to_dict( exclude=['created_at', 'updated_at', 'original_dict', 'id'], ) change = False for key in set(list(actual_dict.keys()) + list(original_dict.keys())): if original_dict.get(key) != actual_dict.get(key): change = True if key == sensitive_fields: changed_field_labels[key] = {'change': 'field updated'} else: changed_field_labels[key] = { 'from': original_dict.get(key, '-'), 'to': actual_dict.get(key, '-'), } if change: json_message = json.dumps( {'changed': {'fields': changed_field_labels}}, cls=ModelEncoder ) # This method creates a log instance.save_edition(user, json_message) For example, consider a model Event that has a many to many field to EventCategory called categories. If changes were made to an event through an UpdateView, for example (including … -
Using Django how can I render in a recursive python function before each return?
I am stuck on this. A function runs recursively changing objects each time. I want to render a updated view before every return. How can I render the template on every step of the python function recursive call? Or how can I approach this problem? Here is my function below: def solveBoard(box, board, size): if box.isFinalValue: newY = box.y newX = box.x + 1 if newX >= size: newX = 0 newY = newY + 1 if newY >= size: return True if solveBoard(board[newY][newX], board, size): return True return False else: allPossibleValues = getAllPossibleValues(box, board, 9) if not allPossibleValues: return False else: for i in allPossibleValues: board[box.y][box.x].numValue = i board[box.y][box.x].isEmpty = False newY = box.y newX = box.x + 1 if newX >= size: newX = 0 newY = newY + 1 if newY >= size: return True if solveBoard(board[newY][newX], board, size): return True board[box.y][box.x].numValue = 0 board[box.y][box.x].isEmpty = True return False -
least memory comsuming way of saving large python data into DB
I have to save a significantly large python data into the a mysql database which consists of lists and dictionaries (0.4MB) but I get memory exception during the save operation. I have already benchmarked the saving operation and also tried different ways of dumping the data, including binary format but all methods seemed to consume a lot of memory. Benchmarks below: PYTHON DATA SIZE: 0.4MB MAX MEMORY USAGE DURING JSON SAVE: 966.83MB SIZE AFTER DUMPING json: 81.03 MB pickle: 66.79 MB msgpack: 33.83 MB COMPRESSION TIME: json: 5.12s pickle: 11.17s msgpack: 0.27s DECOMPRESSION TIME: json: 2.57s pickle: 1.66s msgpack: 0.52s COMPRESSION MAX MEMORY USAGE: json dumping: 840.84MB pickle: 1373.30MB msgpack: 732.67MB DECOMPRESSION MAX MEMORY USAGE: json: 921.41MB pickle: 1481.25MB msgpack: 1006.12MB msgpack seems to be the most performant library but the decompression takes up a lot of memory too. I also tried hickle which is said to consume little memory but the final size ended up being 800MB. Does anyone have a suggestion? Should I just increase the memory limit? can mongodb handle the save operation with less memory? -
Ordering search results by date in Django
I'm trying to order the results of my search by the publication date, where the filter offers two choices: Order by lastest first or the most recent first. This is the filter that I've created so far to do that: filters.py class PubFilters(django_filters.FilterSet): CHOICES = ( ('Fecha', 'Más reciente'), ('Fecha', 'Menos reciente' ) ) ordering = django_filters.ChoiceFilter(label="Ordenar por", choices=CHOICES) class Meta: model = publicaciones fields = ['Precio', 'Categoría'] However, this returns "Cannot resolve keyword 'ordering' into field". And worse: Because I replaced the results for the filtered results (as you can see below), my pagination is suddenly broken, I can see the numbers but paginate_by isn't working. views.py class PostListView(ListView): model = publicaciones template_name = 'store/search.html' context_object_name = 'queryset' ordering = ['Promocionado'] paginate_by = 2 def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) MyFilter = PubFilters(self.request.GET, queryset=self.get_queryset()) context['filter'] = MyFilter context['filtered_items'] = MyFilter.qs context['count'] = self.get_queryset().count() context['búsqueda'] = self.request.GET.get('q') return context def get_queryset(self): qs = self.model.objects.all().order_by('id') search = self.request.GET.get('q') if search: qs = qs.filter(Título__icontains=search) return qs How could I show the filter for "ordering date" correctly? Thanks in advance! -
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 } } }