Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
m2m django implementation after following a tutorial
Scenario: I have some boxes (containers) I have some objects (samples) a sample can be split over many boxes, a box can contain many samples. I want to be able to assign a sample to a box and remove a sample from a box. I followed these tutorials 57-59, assigning friends to users, and got it working. So I now try to adapt the code, so I need to change users to boxes/containers and friends to samples. Sounds simple enough. But I'm inexperienced with the quirks of Django and where the request.user is I can't seem to get the correct syntax. So here comes the code, first the code working from the tutorial, then my attempt at refactoring it. I have 2 other tables/models Containers and Sample which the ContainerContent model fits inbetween. # models.py (tutorial) class Friend(models.Model): users = models.ManyToManyField(User) current_user = models.ForeignKey(User, related_name='owner', null=True, on_delete = models.PROTECT) # container_id = models.ForeignKey(Container, null=True, on_delete = models.PROTECT) @classmethod def make_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create( current_user=current_user ) friend.users.add(new_friend) @classmethod def lose_friend(cls, current_user, new_friend): friend, created = cls.objects.get_or_create( current_user=current_user ) friend.users.remove(new_friend) # views.py def change_friends(request, operation, pk): friend = User.objects.get(pk=pk) if operation == 'add': Friend.make_friend(request.user, friend) elif operation == 'remove': … -
How to submit Django form using Javascript?
I have the following Django form: class EmailForm(forms.Form): name = forms.CharField(...) email = forms.CharField(...) message = forms.CharField(...) Which I then render in my HTML like so: <div class="controls"> {% csrf_token %} <div class="form-group"> {{ form.name }} </div> <div class="form-group"> {{ form.email }} </div> <div class="form-group"> {{ form.message }} </div> <input type="submit" value="Say hello" onclick="sendEmail(this);"> </div> I'm trying to disable the submit button after it's pressed. Here's my javascript function: <script> function sendEmail(this1) { var name = document.getElementById("form_name").value; var email = document.getElementById("form_email").value; var message = document.getElementById("form_message").value; var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var result = re.test(String(email).toLowerCase()); if (name != "" && result && message != "") { this1.disabled=true; } } </script> When I override the onclick field in the <input> tag, the button becomes disabled as a result of the Javascript function, but the form does not submit (the page is not reloaded, Django doesn't process the POST). How do I continue the default action for the submit button after disabling it? -
How can I debug this transpilation problem in webpack? It disappears if I set minimize to true
I'm developing a django application with a reactjs front end that uses webpack for hot serving of javascript during development. Versions are pretty much all the latest: "devDependencies": { "@babel/cli": "^7.2.3", "@babel/core": "^7.4.0", "@babel/plugin-proposal-object-rest-spread": "^7.4.0", "@babel/plugin-syntax-jsx": "^7.2.0", "@babel/polyfill": "^7.4.0", "@babel/preset-env": "^7.4.2", "@babel/preset-react": "^7.0.0", "ajv": "^6.10.0", "auto-bind": "^1.2.1", "babel-loader": "^8.0.5", "bluebird": "^3.5.1", "chai": "^4.2.0", "chai-as-promised": "^7.1.1", "chart.js": "^2.8.0", "css-loader": "^2.1.1", "d3": "^5.9.2", "deep-equal": "^1.0.1", "enzyme": "^3.9.0", "file-loader": "^3.0.1", "fusioncharts": "^3.13.4", "history": "^4.9.0", "immutability-helper": "^2.9.1", "jquery": "^3.3.1", "jquery.cookie": "^1.4.1", "js-yaml": "^3.13.0", "jsdom": "^14.0.0", "lodash": "^4.17.11", "mocha": "^4.1.0", "moment": "^2.24.0", "query-string": "^5.1.1", "react": "^16.8.5", "react-addons-update": "^15.6.2", "react-bootstrap": "^0.31.5", "react-codemirror": "^1.0.0", "react-dom": "^16.8.5", "react-dropzone": "^4.3.0", "react-fusioncharts": "^1.0.5", "react-hot-loader": "^3.1.3", "react-input-autosize": "^2.2.1", "react-numeric-input": "^2.2.3", "react-popper": "^0.8.3", "react-redux": "^6.0.1", "react-router-dom": "^4.3.1", "react-select": "^2.4.2", "react-sortable-hoc": "^1.8.3", "react-table": "^6.9.2", "react-tooltip": "^3.10.0", "reconnecting-websocket": "^4.1.10", "redux": "^3.7.2", "redux-form": "^8.1.0", "redux-logger": "^3.0.6", "redux-thunk": "^2.3.0", "select2": "^4.0.6-rc.1", "style-loader": "^0.23.1", "sunburst-chart": "^1.3.1", "url-loader": "^1.1.2", "uuid": "^3.3.2", "webpack": "^4.29.6", "webpack-bundle-tracker": "^0.3.0", "webpack-cli": "^3.3.0", "webpack-dev-server": "^3.2.1" } During development with the hot server running, everything works as expected. If I switch to production mode and use the main.js file which builds without warnings or error, The code fails in the browser with "Uncaught SyntaxError: Unexpected token (" on this line of the main.js: function(e,t){if("function"!=typeof t&&null!==t)throw … -
How to use jQuery .load() to get {% block content %} in django?
I'm learning web development with django. Currently I'm trying to realize a function that when I click "login" button the website will show a modal which contains the <div id="log-in">. this div is from login.html I firstly tried $('#test_modal').load('/accounts/login/ #log-in').modal('show') but it didn't work. I tried similar function to get div from pages where I didn't use {% block content %} and it works. So I'm quite confused right now. Here is my login.html code: <div id="log-in"> {% extends "account/base.html" %} {% load i18n %} {% load account socialaccount %} {% block head_title %}{% trans "Sign In" %}{% endblock %} {% block content %} <h1>{% trans "Sign In" %}</h1> {% get_providers as socialaccount_providers %} {% if socialaccount_providers %} <p>{% blocktrans with site.name as site_name %}Please sign in with one of your existing third party accounts. Or, <a href="{{ signup_url }}">sign up</a> for a {{ site_name }} account and sign in below:{% endblocktrans %}</p> <div class="socialaccount_ballot"> <ul class="socialaccount_providers"> {% include "socialaccount/snippets/provider_list.html" with process="login" %} </ul> <div class="login-or">{% trans 'or' %}</div> </div> {% include "socialaccount/snippets/login_extra.html" %} {% else %} <p>{% blocktrans %}If you have not created an account yet, then please <a href="{{ signup_url }}">sign up</a> first.{% endblocktrans %}</p> {% endif %} … -
Django AppName issue
I get the error after typing the code in the models.py field after determining the application name in urls.py No problem before defining the application name. urls.py from django.urls import path, re_path from .views import * AppName = 'Post' urlpatterns = [ re_path(r'^Index/$', PostIndex, name='Index'), re_path(r'^(?P<id>\d+)/$', PostDetail, name='Detail'), re_path(r'^Create/$', PostCreate, name='Create'), re_path(r'^Update/$', PostUpdate, name='Update'), re_path(r'^Delete/$', PostDelete, name='Delete'), ] models.py from django.db import models from django.urls import reverse # Create your models here. class Post(models.Model): Title = models.CharField(max_length=120) Content = models.TextField() PublishingDate = models.DateTimeField() def __str__(self): return self.Title def get_absolute_url(self): return reverse('Post:Detail', kwargs={'id':self.id}) Index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {% for Post in Posts %} {{ Post.id }}<br> <a href="{{ Post.get_absolute_url }}">{{ Post.Title }}</a><br> {{ Post.Content }}<br> {{ Post.PublishingDate }}<br> {% endfor %} </body> </html> I am not receiving an error without defining the application name in the models.py field. There is an error in code editing in the models.py field. def get_absolute_url(self): seamless code => return reverse('Detail', kwargs={'id':self.id}) problematic code => return reverse('Post:Detail', kwargs={'id':self.id}) How do I write the problematic code to avoid getting the error? -
Getting 400's from aws ELB hostcheck to work with django ALLOWED_HOSTS in aws ECS under awsvpc networking mode?
When moving over to ECS with awsvpc networking mode, my ALB says all my hosts are unhealthy because checking /status/ yields 400s. I've narrowed it down to the issue being something wrong with ALLOWED_HOSTS. How do I get my web app to give 200's to the ELB Healthchecker? -
How can I customize an table inputed by django views
How can I customize the input from Django views? So I want to make the Django input from the SQL Database look more like this: PS: IN GITHUB SCORE ITS THE DATE Since it is input from the Database I cant individually code them so I need a way to make a code universal for all new input from Django database! Django input: CODEX Python March 11, 2019 Python-NMAP-ULTRA Python Feb. 3, 2019 My CODE: @font-face { font-family: RobotoLight; src: local('{% static "fonts/ROBOTO" %}'), url('Roboto-Light.ttf') format('ttf'); } body{ background-color: #FFFFFF; height: 100%; width: 100%; } /*MENU*/ #MENU{ font-family: 'RobotoLight', sans-serif; } .background{ position: absolute; top: 0%; left: 0%; width: 100%; height: 15.5%; background-color: black } .logo{ position: absolute; top: 1.5%; left: 12%; width: 7%; height: auto; } .logo:hover{ position: absolute; text-decoration: none; color: white; -webkit-animation: LogoAnimation; /* Safari 4.0 - 8.0 */ -webkit-animation-duration: 0.2s; /* Safari 4.0 - 8.0 */ animation: LogoAnimation; animation-duration: 0.2s; animation-fill-mode: both; } /* Safari 4.0 - 8.0 */ @-webkit-keyframes LogoAnimation { from { top: 1.5%; left: 12%; width: 7%; height: auto; } to { top: 0.8%; left: 11.5%; width: 8%; height: auto; } } @keyframes LogoAnimation { from { top: 1.5%; left: 12%; width: 7%; … -
How to Create a Webscrapper using Django and Scrapy?
Having a problem when running a spider in order to get the info needed from the website. The idea is to get info from a website through Scrapy and display it on Django Website, but after following every tutorial found I got an error always either on the spiders which are unable to run or in the models since you cannot asign a user to them the same way as previous. models.py from django.db import model class Jobs(models.Model): name = models.CharField(max_length=150) image = models.CharField(max_length=150) description = models.CharField(max_length=150) items.py from scrapy_djangoitem import DjangoItem from project.models import Jobs class JobsItem(DjangoItem): django_model = Jobs scraper/urls.py import scrapy from scraper.items import JobsItem class Spider(scrapy.Spider): name = "jobs" start_urls = ["https://www.jobs.com"] # this is what start_urls does # def start_requests(self): # urls = ['https://www.jobs.com',] # for url in urls: # yield scrapy.Request(url=url, callback=self.parse) def parse(self, response): data = response.css("div.st-about-employee-pop-up") for line in data: item = JobsItem() item["name"] = line.css("div.h3 h3::text").extract_first() item["image"] = line.css("img.img-team-popup::attr(src)").extract_first() item["description "] = line.css("div.p-small p::text").extract().pop() yield item pipelines.py class JobsPipeline(object): def process_item(self, item, spider): item.save() return item scraper/settings.py ITEM_PIPELINES = {"scraper.pipelines.JobsPipeline": 300} Can´t really see how this can be joined to Django since it can´t seem to accept crawl command giving me … -
Django Celery Max DB connections reached
I am running tasks on my celery worker in a django application where each task takes about 1-2 seconds to execute. Usually these executions are fine but from time to time, especially if the Django application has been deployed for a while, I start seeing errors like this: File "/usr/lib64/python3.6/site-packages/sqlalchemy/pool/base.py", line 428, in __init__ self.__connect(first_connect_check=True) File "/usr/lib64/python3.6/site-packages/sqlalchemy/pool/base.py", line 630, in __connect connection = pool._invoke_creator(self) File "/usr/lib64/python3.6/site-packages/sqlalchemy/engine/strategies.py", line 114, in connect return dialect.connect(*cargs, **cparams) File "/usr/lib64/python3.6/site-packages/sqlalchemy/engine/default.py", line 453, in connect return self.dbapi.connect(*cargs, **cparams) File "/usr/lib64/python3.6/site-packages/psycopg2/__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) FATAL: remaining connection slots are reserved for non-replication superuser connections Which indicates to me that the Celery worker is not closing connections properly. I checked the idle connection count on the DB when this error occurred -- there were definitely some connections left so the DB's max connection limit was not reached. My question: How can I ensure that the celery worker is closing DB connections? Celery settings: app = Celery('my_proj', broker=_celery_broker, backend=_result_backend) app.autodiscover_tasks(['common']) app.conf.update( worker_prefetch_multiplier=0, event_queue_ttl=0, task_acks_late=True, ) My Django DB settings: 'DATABASES': { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': <...>, 'USER': <...>, 'PASSWORD': <...>, 'HOST': <...>, 'PORT': 5480, } } How I start my … -
How to allow users creation and authentication in django-rest-framework
Hi I want to create users and perform authentication using HTTP request using modelviewset in Django-Rest-Framework ? Is there any way to do this ? -
How do I set up a view/path to an AJAX call in Django?
I'm using Django and Python 3.7. I have this file in my project web/views/tax_calculator.py which consists of a single function (I'm leaving out the imports) ... def calculate_taxes(request): state = request.GET.get('state', None) gross_income = request.GET.get('gross', None) owner_salary = request.GET.get('salary', None) data = { 'sole_pr_taxes': TaxCalculatorService.calc_sole_pr_taxes(state, gross_income), 's_corp_taxes': TaxCalculatorService.calc_s_corp_taxes(state, gross_income, owner_salary), } return JsonResponse(data) In my ./myproject/urls.py file I have from django.contrib import admin from django.urls import path from web.views import * urlpatterns = [ path(r'^ajax/calculate_taxes/$', tax_calculator.calculate_taxes, name='calculate_taxes'), ] but this results in an error path(r'^ajax/calculate_taxes/$', tax_calculator.calculate_taxes, name='calculate_taxes'), NameError: name 'tax_calculator' is not defined What's the right way to reference my view/AJAX call? -
Django template fails to evaluate only when looking up a certain field
I am working through Section 3 of the official Django tutorial and having trouble with template variable evaluation. After adding app_name = polls to my urls.py and updating {% url 'detail' question.id %} to {% url 'polls:detail' question.id %} in my template, my template is no longer successfully evaluating one of the fields in each instance of Question. With the below code, question.question_text in polls/index.html is not being evaluated. Instead, literally {{ question.question_text }} is being displayed for each list item. However, when I change question.question_text to question.pub_date (pub_date is another field on the object), it is properly evaluated and the date is displayed. Additionally, question is evaluated to the question.question_text value I am looking for because of the Question class' __str__ method. polls/urls.py from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] polls/views.py import datetime from django.db import models from django.utils import timezone class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) polls/index.html {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li> <a href="{% url 'polls:detail' … -
Django REST Framework & Lifecycle of a Django Model instance
I have a django-rest-framework app that currently makes heavy use of computed properties in my models and my serializers. For (overly-simplified) example: models.py class Person(models.Model): first_name = models.CharField() last_name = models.CharField() @property full_name(self): return first_name + last_name serializers.py class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = ("first_name", "last_name", "full_name") I am interested in using Django's @cached_property instead of @property, in hopes of speeding things up, since the values being computed here shouldn't really change more than once a day. I am unsure, though, if @cached_property will actually effect how quickly DRF returns it's JSON response. The Django docs say: The @cached_property decorator caches the result of a method with a single self argument as a property. The cached result will persist as long as the instance does, so if the instance is passed around and the function subsequently invoked, the cached result will be returned. So I'm wondering what is the lifecycle of a Django model instance? Will it be created every time a call is made to a DRF view? And if so, are there alternative approaches to achieving my goal? -
Is there somewhere i can run manage.py command line in VS2019?
I'm looking to run manage.py command line to load data from my model with something like python manage.py loaddata mytest I'm using Visual Studio 2019 to be more familiar with the new version. But i'm unable to run manage.py command line. Does someone experieced with how i can manage my django environment on Visual Studio 2019? I can use 'normal' fonction on Python option like Make migration, migration, etc.. But i'm lost on how i can use other manage.py function. Thanks for your help. -
Django - How to query the most recent distinct rows before an effective date?
I have a model full of effective dated rates. The notable fields on these rates are name, type, effective_date, and rate. I need to be able to filter the modifier rates to get only rates of a certain type and before a certain date. ModifierRate.objects.filter( type=settings.MODIFIER_RATE_TYPES_TAX, effective_date__lte=date) That query may return rates with the same name and type so I need them to be distinct on those two fields. .distinct('name', 'type')` However, if there is a duplicate name and type I need the most recent one. .order_by('-effective_date') After all that I need to aggregate Sum the rates on those objects. .aggregate(rate__sum=Coalesce(Sum('rate'), 0))['rate_sum'] If I try and smash all these things together I get raise NotImplementedError("aggregate() + distinct(fields) not implemented.") NotImplementedError: aggregate() + distinct(fields) not implemented. I've been googling for awhile and there are many similar questions that make use of values_list and annotate but I don't think that's what I want. How do I get the sum of the rates before a certain date that are distinct on fields name and type where the most recent distinct rate is used? Thanks. -
Django to retrieve error messages in case the user does not do any option select or POST
I am trying to see when a user clicks the "submit" button without POSTING--that it'll give error messages informing the user to click on option values. It gives an error stating that MultikeyValue Error at 'venue'. When I select, it is able to POST just fine--but I am trying to retrieve error messages in case the user does not select any. models.py class Ticket(models.Model): venue=models.CharField(max_length=100) quantity=models.PositiveIntegerField() price=models.DecimalField(default=25.00, max_digits=5, decimal_places=2, null=True, blank=True) loop=models.CharField(max_length=100) purchaser = models.ForeignKey(User, related_name="purchases", on_delete=models.PROTECT) created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now=True) dashboard.html <form action="/add" method="POST"> {% csrf_token %} <div class="text-center"> {% if messages %} {% for message in messages %} <div class="alert alert-danger p-2 pb-3"> <a class="close font-weight-normal initialism" data-dismiss="alert" href="#"><samp>×</samp></a> {{message}} </div> {% endfor %} {% endif %} <label><strong>Location of Venue:</strong></label> <select class="form-control" name="venue"> <option value="" selected disabled>Please select</option> <option value="San Bernardino">San Bernardino</option> <option value="Los Angeles">Los Angeles</option> <option value="Riverside">Riverside</option> </select> <button type="submit" value="/add" class="btn btn-dark">Buy Tickets</button> </form> views.py def add(request): if not 'user_id' in request.session: return redirect('/chrisgrafil') if request.method!='POST': return redirect ('/dashboard') error=False if len(request.POST['venue'])<1: messages.error(request, "Please select venue") error=True if len(request.POST['quantity'])<1: messages.error(request, "Please select quantity") error=True if len(request.POST['loop'])<1: messages.error(request, "Please select loop") error=True else: Ticket.objects.create(venue=request.POST['venue'], quantity=request.POST['quantity'], loop=request.POST['loop'], purchaser=User.objects.get(id=request.session['user_id'])) return redirect ('/confirmation') -
How to set instances of class to a drop list in widget forms.Select
I try to make in template a select list with an objects from database. I figured out that i can use widget form.select and set a choices of a objects from database but instead manually I would like to do this by some for loop? forms.py ''' from django.forms import ModelForm from django import forms from .models import Ship class ShipForm(ModelForm): class Meta: model = Ship fields = ['name','rolls','rolls_del'] all_instance = Ship.objects.all() INSTANCE_CHOICES = (('1111','1111'),('333','333'), ('11','11')) widgets = {'name':forms.Select(choices=INSTANCE_CHOICES)} ''' and here in INSTANCE_CHOICES I would like to have some for loop or maybe some method to fill out automatically models.py ''' from django.db import models from django.forms import ModelForm class Ship(models.Model): name = models.CharField(max_length = 20) rolls = models.IntegerField(null = True) rolls_del = models.IntegerField(default=0) total = models.IntegerField(default=0) def __str__(self): return self.name ''' views.py ''' def data(request): ships = Ship.objects.all().order_by('name') for x in ships: x.total = x.rolls - x.rolls_del cont = {'ships':ships} return render(request,'data.html', context=cont) ''' -
I keep getting no changes detected when migrating app in Django
I am following this video tutorial to learn Django: https://www.youtube.com/watch?v=F5mRW0jo-U4&t=909s I am at the "Your first app component" section where he creates an app and then migrates it. I have followed every one of his steps so far yet I keep getting the no changes detected error when I migrate the app I have tried researching ways to fix this but it doesn't seem like there is any one right way to do it, it's more of a case by case basis. I've made sure my app is under the install_apps section in the settings. I've tried python manage.py makemigrations but that tells me there are no changes detected. I've tried "python manage.py makemigrations product" to be more specific but it tells me that App 'product' could not be found. Is it in INSTALLED_APPS?" even though it is in installed apps currently this is my installed apps section: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'product', -
How to specify optional parameters on Django REST Framework ViewSet @action method?
I've got a ViewSet class with a method like this: @action(methods=["get"], detail=True, url_path="foo") def foo(self, request: Request, pk: int) -> Response: limit = request.query_params.get("limit") if limit is not None: limit = int(limit) … I would like to declare the method so that the generated OpenAPI specification documents this optional parameter, ideally in such a way that I don't have to manually mess around with pulling out the variable and converting it. Something like this would be ideal: def foo(self, _: Request, pk: int, limit: Optional[int] = None) -> Response: -
Save HTML canvas to django 2 database
I am using the Mobile Camera Template https://github.com/kasperkamperman/MobileCameraTemplate. I have the repo working as a Django 2 app but I wish to save the image from the canvas to the Django database (SQLite) when the "Take Photo" button is pressed. <button id="takePhotoButton" name="take Photo" type="button"></button> I want the image to be save in the DB and be displayed with all the others in a list. I have my list working with existing files, but I cannot work out how to get a new image/photo from the canvas to the model. # models.py class Document(models.Model): docfile = models.FileField(upload_to='documents/%Y/%m/%d') # views.py def camera(request): context = { } return render(request, 'index.html', context) Please can anyone help? Thanks, Jon -
Connecting serializers through a non primary key question
I'm having trouble creating a relationship between Project and Token, i want to display all tokens for a project in the project json result. The PK of the project is stored in the project column in Token. models.py class Project(models.Model): name = models.CharField(max_length=50) class Token(models.Model): project = models.ForeignKey(Project,on_delete=models.CASCADE,blank=True) symbol = models.CharField(max_length=50) serializers.py class TokenSerializer(serializers.ModelSerializer): allow_null=True class Meta: model = Token fields = ('id','symbol') class ProjectSerializer(serializers.ModelSerializer): development = DevelopmentSerializer() tokens = TokenSerializer() class Meta: model = Project fields = ('id','name','tokens') The result i would like: { "id": 1, "name": "Bitcoin", "tokens": [ "id": 1, "symbol": "BTC" ] } At this time i get the following error: Got AttributeError when attempting to get a value for field tokens on serializer ProjectSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Project instance. Original exception text was: 'Project' object has no attribute 'tokens'. -
Unknown field(s) () specified for
what is wrong here? error: File "/Users/user/Desktop/Dp1/project6/project6/urls.py", line 18, in from myapp6 import views File "/Users/user/Desktop/Dp1/project6/myapp6/views.py", line 2, in from myapp6.forms import UserForm,UserProfileInfoForm File "/Users/user/Desktop/Dp1/project6/myapp6/forms.py", line 15, in class UserProfileInfoForm(forms.ModelForm): File "/Users/user/miniconda3/envs/Djangoenv/lib/python3.7/site-packages/django/forms/models.py", line 266, in new raise FieldError(message) django.core.exceptions.FieldError: Unknown field(s) (profile_pic) specified for UserProfileInfo models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfileInfo(models.Model): user = models.OneToOneField(User,on_delete='models.PROTECT') portfolio_site = models.URLField(blank=True) portfolio_pic = models.ImageField(upload_to='profile_pics',blank=True) def __str__(self): return self.user.username forms.py from django import forms from django.contrib.auth.models import User from myapp6.models import UserProfileInfo class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields = ('username','email','password',) class UserProfileInfoForm(forms.ModelForm): class Meta(): model = UserProfileInfo fields = ('portfolio_site','profile_pic') -
Merge 2 cache entries into one
There are invoices that I am caching but with 2 cache entry. First cache entry holds if caching of the invoices are existing or not. Why I am doing it? Because there is a business logic (get_cache_timeout method) that tells me when to update 2nd cache entry which is holding the actual invoice details. So, first one is a flag for me to understand if 2nd cache entry is there or not. If not, I call the backend system and update 1st and 2nd cache entry. The reason behind of having 2nd cache key with 60 days is that, for the worst case if 1st entry doesn't exist and then call to the backend system fails, I want to still return 2nd cache entry as a response instead of showing error. cache.set(f'{invoices}_cache_exists', True, get_cache_timeout()) cache.set(f'{invoices}_cache', some_cache, 60*60*24*60) Sorry for confusing explanation but I hope you get the idea behind of this solution. So, in the end my question is that for this problem how can I get rid of 1st cache entry and only having 2nd cache entry with 2 timeouts? 1st one is giving me telling when to update, and 2nd one is to remove the cache. -
handle dynamic nested inline formsets in django templates
I want to add parent and Dynamically add relevant children with it, and when i click (add child) it add it to the relevant parent. I am currently using 'django-dynamic-formset' my template: {% load crispy_forms_tags %} {% load staticfiles %} <table class="col-md-9" style="margin-left: 10px;"> {{ formset.management_form|crispy }} {% for form in formset.forms %} <tr class="formset_row-{{ formset.prefix }}"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field|as_crispy_field }} </td> {% endfor %} </tr> <!--nested form--> {% if form.nested %} {{ form.nested.management_form }} {{ form.nested.non_form_errors }} {% for nested_form in form.nested.forms %} <tr class="{% cycle 'row1' 'row2' %} formset_child-{{ formset.prefix }}"> {% for fields in nested_form.visible_fields %} <td> {# Include the hidden fields in the nested_form #} {% if forloop.first %} {% for hidden in nested_form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ fields.errors.as_ul }} {{ fields|as_crispy_field }} </td> {% endfor %} </tr> {% endfor %} {% endif %} <!-- end of nested form--> {% endfor %} </table> <br> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="{% static 'mycollections/libraries/django-dynamic-formset/jquery.formset.js' %}"></script> <script … -
How to expire password reset token after password changed?
I set up a password reset functional in Django. I wonder how to expire password reset URL after it was used to reset password