Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to redirect after server side process finishes in Python's Django Framework
The general idea of what's supposed to happen: the user logs in the login info gets passed to an API the user is redirected to a loading page if it's a valid login the server side script in views.py pulls some data from the user's account once that finishes it redirects to the main page which displays infographics based off of that data. The problem I'm having is that the rendering of the loading.html is skipped after the login function redirects to the loading function, and the loading function redirects to the dashboard which displays the infographics after a long loading time while the script finishes server side. Currently, the loading function in views.py looks like this: def loading(request): username = request.session['username'] password = request.session['password'] API = APILogin(username, password) #pull data from API functions if data_pull_is_finished = True: #save data to database server return redirect('dashboard') else: #keep pulling data from API return render(request, 'loading') Any advice? I'm really new to Django (a week to be precise) and I've already gone through 2 tutorials and done multiple searches in regards to this, so please don't roast me too much for a newbie question. It's similar to: Django redirect to results page … -
How do I use x-editable with django?
I'd like to know how I can use an x-editable in django to replace a form with a few editable tags and be able to send that information to the view. -
Adding a message without a text in Django's messages framework
Sometimes I would like to trigger a message to the user with the message's text defined in the client-side JS code. I am using the message framework's tags to differentiate between the different messages in JS. Unfortunately, it seems to me that when I call messages.add_message with the message text set to None and a number of tags, the message is discarded. Is there are a way to send a message without text in Django? -
Django Unittest failing to run with TypeError: isinstance() arg 2 must be a type or tuple of types on one machine but not others
For some reason I cannot run "manage.py test AppNameHere" on my Windows machine but when I run it on a linux machine (I'm not sure if the OS actually matters here) the tests run fine. I am getting this error: 2019-01-11 17:35:32 [DEBUG] faker.factory: Not in REPL -> leaving logger event level as is. Creating test database for alias 'default'... Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Users\personA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\personA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\personA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\test.py", line 26, in run_from_argv super().run_from_argv(argv) File "C:\Users\personA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\personA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "C:\Users\personA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\test.py", line 56, in handle failures = test_runner.run_tests(test_labels) File "C:\Users\personA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\test\runner.py", line 604, in run_tests old_config = self.setup_databases() File "C:\Users\personA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\test\runner.py", line 551, in setup_databases self.parallel, **kwargs File "C:\Users\personA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\test\utils.py", line 174, in setup_databases serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True), File "C:\Users\personA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\backends\base\creation.py", line 68, in create_test_db run_syncdb=True, File "C:\Users\personA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\__init__.py", line 148, in call_command return command.execute(*args, **defaults) File "C:\Users\personA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "C:\Users\personA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\personA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\management\commands\migrate.py", line 203, in handle fake_initial=fake_initial, File "C:\Users\personA\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, … -
How to make a class JSON serializable for usage in Django session
I try to store in Django session the following pretty much arbitrary class: class QuizInfo: def __init__(self): self.i_active_question = INVALID_PQA_ID # integer self.sequence = [] In turn, each item of QuizInfo.sequence list is an instance of AnsweredQuestion: class AnsweredQuestion: def __init__(self, i_question, i_answer): self.i_question = i_question self.i_answer = i_answer I try to store such a data structure in HttpRequest.session like the following: qi = QuizInfo() qi.i_active_question = 5 # e.g. qi.sequence.append(AnsweredQuestion(1, 2)) # e.g. qi.sequence.append(AnsweredQuestion(3, 4)) # e.g. quiz_id = 7 # e.g. request.session['quiz_infos'] = {quiz_id : qi} So request.session['quiz_infos'] is a dictionary of int keys and QuizInfo values. I get the following error: Traceback: File "C:\Users\Sarge\Envs\PqaWeb1\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\Sarge\Envs\PqaWeb1\lib\site-packages\django\utils\deprecation.py" in __call__ 93. response = self.process_response(request, response) File "C:\Users\Sarge\Envs\PqaWeb1\lib\site-packages\django\contrib\sessions\middleware.py" in process_response 58. request.session.save() File "C:\Users\Sarge\Envs\PqaWeb1\lib\site-packages\django\contrib\sessions\backends\db.py" in save 83. obj = self.create_model_instance(data) File "C:\Users\Sarge\Envs\PqaWeb1\lib\site-packages\django\contrib\sessions\backends\db.py" in create_model_instance 70. session_data=self.encode(data), File "C:\Users\Sarge\Envs\PqaWeb1\lib\site-packages\django\contrib\sessions\backends\base.py" in encode 96. serialized = self.serializer().dumps(session_dict) File "C:\Users\Sarge\Envs\PqaWeb1\lib\site-packages\django\core\signing.py" in dumps 87. return json.dumps(obj, separators=(',', ':')).encode('latin-1') File "c:\programs\python37\Lib\json\__init__.py" in dumps 238. **kw).encode(obj) File "c:\programs\python37\Lib\json\encoder.py" in encode 199. chunks = self.iterencode(o, _one_shot=True) File "c:\programs\python37\Lib\json\encoder.py" in iterencode 257. return _iterencode(o, 0) File "c:\programs\python37\Lib\json\encoder.py" in default 179. raise TypeError(f'Object of type {o.__class__.__name__} ' Exception Type: TypeError at / Exception Value: … -
How can I pip install for development?
I'm trying to pip install a GitHub project locally, outside of site-packages so that I can modify it, etc. I've added -e git+git@github.com:Starcross/django-starcross-gallery.git#egg=gallery to my requirements.txt which brings the relevant part of my project layout to look like this: /home/mat/venv/proj/ └── src └── django-starcross-gallery ├── admin.py ├── apps.py ├── build.sh ├── django_starcross_gallery.egg-info │ ├── dependency_links.txt │ ├── PKG-INFO │ ├── requires.txt │ ├── SOURCES.txt │ └── top_level.txt ├── forms.py ├── __init__.py ├── LICENSE ├── MANIFEST.in ├── models.py ├── README.rst ├── settings.py ├── setup.py ├── signals.py ├── static │ └── ... ├── templates │ └── ... ├── tests │ └── ... ├── tests.py ├── urls.py └── views.py As far as I can see the problem is that these .egg-link and .pth files like one level too deep: lib/python3.6/site-packages/django-starcross-gallery.egg-link: /home/mat/venv/proj/src/django-starcross-gallery . lib/python3.6/site-packages/easy-install.pth: /home/mat/venv/proj/src/django-starcross-gallery I can fix everything by either moving django-starcross-gallery a level deeper, or changing django-starcross-gallery.egg-link and easy-install.pth to point to src. Is there a config parameter I can pass in requirements.txt to make this work properly? Or do I have to adjust the project layout to fit? -
OneToMany "must be an instance" Django
I'm experimenting to get a better idea of how Django works. Take the below test function that creates a Category, Tag, and Item representing Macbook Pros then adds a Macbook Pro to that Category, Tag, and Item (product). def make_macbook(): """ Create a Manufacturer for Apple """ apple = Manufacturer(name='Apple', rep_name='Jason Wilburn', support_number='1-800-Apple') apple.save() print('Manufacturer name: {}'.format(apple)) """ Create a Category for Laptops """ laptop = Category(name='Laptops') laptop.save() print('Category name: {}'.format(laptop)) """ Create a Tag for Mac """ mac = Tag(title='mac') mac.save() print('Tag name: {}'.format(mac)) """ Create a MacBook Item """ macbook = Item(name='Macbook Pro', description='15.5" Macbook Pro, 2018 Model', manufacturer=apple) macbook.save() print('Item name: {}'.format(macbook)) """ Create a MacBook OnHand item """ newMac = OnHand(name='MacBook Pro 15.5"', serial='SC02XP0NRJGH5', asset='DEPSC02XP0NRJGH5', product=macbook) newMac.save() return newMac.product What I'm testing now is adding new OnHand objects to the Category, Tag, and Item. Here is what I have: def add_macbook(): """ Find MacBook Item """ macbook = Item.objects.filter(name='Macbook Pro') """ Create a MacBook OnHand item """ newMac = OnHand(name='MacBook Pro 15.5"', serial='000000000000000', asset='DEP0000000000000', product=macbook) newMac.save() I'm confronted with 2 problems: Class 'Item' has no 'objects' member ValueError: Cannot assign "]>": "OnHand.product" must be a "Item" instance. How would I get an existing Item instance to … -
Adding Google Custom Search Engine(CSE) to Django Applications
I have the following code that works when I run it as a simple Python Script: import datetime import pprint import json import csv import sys from googleapiclient.discovery import build API_key = "AIzaSyACbRbMXOKeUvp-t2emvzK9ir4q9IbbFK8" cse_key = "006911263525536148912:gvhup_6fuvo" terms = ['trump', 'pelosi', 'democrats', 'republicans'] def main(): with open ("search.csv",'a', newline = '', encoding="utf-8") as search_csv: writer = csv.writer(search_csv) writer.writerow(['Name', 'Article', 'Link', 'SearchDate']) for term in terms: service = build("customsearch", "v1", developerKey=API_key) res=service.cse().list(q=term,cx=cse_key,num=10,exactTerms="shutdown").execute() articles = res.get('items',[]) for article in articles: date = datetime.datetime.today().strftime('%m-%d-%Y') article = article['title'] link = article['link'] writer.writerow([term, article, link, date]) Now I want to make this into a Django app, but I'm having some issues making it work. views.py from django.shortcuts import render, HttpResponse, redirect, reverse from .models import * import datetime from django.db.models import Q import pprint import json import csv import sys from googleapiclient.discovery import build API_key = "AIzaSyACbRbMXOKeUvp-t2emvzK9ir4q9IbbFK8" cse_key = "006911263525536148912:gvhup_6fuvo" def main(): terms = request.POST.getlist('term',[]) # print (terms) for term in terms: service = build("customsearch", "v1", developerKey=API_key) res=service.cse().list(q=term,cx=cse_key,num=10,/ exactTerms="shutdown").execute() articles = res.get('items',[]) for article in articles: print(term) print(article['title']) print (article['link']) return redirect ((reverse('project:main'))) I read that there is a Google API utility for Django here: https://developers.google.com/api-client-library/python/guide/django The documentation is too advanced for me and I don't … -
How can I create a Django OneToMany Relation?
So, I have been making my first website and hosting it on Heroku. The website's purpose is to post challenges which lead to a specific secret key(kinda like a very easy CTF). When the key is submitted, the challenge is solved. This is the code in my models.py file from django.db import models from django.contrib.auth.models import User class Post(models.Model): """ Each post represents one challenge """ title = models.CharField(max_length=40) text = models.TextField() secret_key = models.CharField(max_length=30) solved = models.BooleanField(default=False, name='solved') file = models.FileField(upload_to='uploads/', null=True, blank=True) # solved_by = models.ForeignKey(User, on_delete=models.CASCADE) def check_state(self, answer): """ Examine whether the challenge was solved """ if self.secret_key == answer: self.solved = True self.save() return True return False def __str__(self): return self.title Each post is basically a challenge. The solved value is set to True when somebody solves the challenge/post and also controls whether the text is visible to the users. Right now, when someone solves a challenge it is being solved for everybody else. I want each user to solve every challenge and has his own solved variable for each challenge. I tried using models.Foreign key, but it won't work. What database relation do I need in order to make this work? -
Django ListView как взять id количество записей в смежной моделе
Подскажите как взять количество коментариев через смежные модели? Или как это проще сделать. Модель сообщений к которым вывожу количество коментариев для каждого сообщения через ListView class Message(models.Model): userID = models.ForeignKey( Account, on_delete=models.CASCADE, verbose_name='Пользователь', null=False, blank=False ) subject = models.CharField( max_length=250, verbose_name='Тема', null=False, blank=False ) type = models.ForeignKey( SeenType, on_delete=models.CASCADE, blank=False, null=False, default=0, max_length=20 ) itemID = models.IntegerField( null=False, blank=False ) text = models.TextField( blank=True, null=True, max_length=500, verbose_name='Описание' ) Модель коментариев class Comment(models.Model): date = datetime.now() userID = models.ForeignKey( Account, on_delete=models.CASCADE, verbose_name='Пользователь', null=False, blank=False ) type = models.ForeignKey( SeenType, on_delete=models.CASCADE, blank=False, null=False, default=0, max_length=20 ) itemID = models.IntegerField( null=False, blank=False ) text = models.TextField( blank=True, null=True, max_length=500, verbose_name='Описание' ) И view контроллер через который пытаюсь вывести список сообщений и в каждом сообщении количестов коментариев к нему class MessageList(LoginRequiredMixin, ListView): """Контроллер списка сообщений""" model = Message context_object_name = 'instance' success_url = reverse_lazy('message:list') login_url = reverse_lazy('accounts:login') paginate_by = 10 def get_queryset(self, **kwargs): query = Message.objects.filter(userID=self.request.user.id).order_by('-created') comment = Account.objects.filter(itemID=self.queryset.values('id')) context = { 'message': query, 'comment': comment } return context Ни как не могу найти информацю как взять из объекта ид сообщения. Мне нужно как то забрать itemID чтоб потом по нему отфильтровать. self.request.itemID не прокатывает. -
Getting "NOT NULL constraint" when submitting form through view. Works fine when adding through /admin
I'm creating a simple ratemyteacher/prof clone. The issue is that when going trying to add a Review object via my view, I get NOT NULL constraint failed: rate_review.review_id (app name is rate). It works fine when adding via /admin. Also, adding other models work fine. Here's the view where it occurs: def add_review(request, teacher_id): teacher = Teacher.objects.get(pk=teacher_id) form = ReviewForm() if request.method == 'POST': form = ReviewForm(request.POST) if form.is_valid(): ip = request.META.get('HTTP_CF_CONNECTING_IP') if ip is None: ip = request.META.get('REMOTE_ADDR') form.customSave() messages.success(request, 'Review added.') else: form = ReviewForm(request.POST) return render(request, 'rate/add_review.html', {'form': form}) return render(request, 'rate/add_review.html', {'form': form}) Here is the form (truncated to exclude loads). I'm using this to render forms: <form method="POST">{% csrf_token %} <div class="field"> <label class="label">Stars (whole numbers only)</label> <div class="control"> {% render_field form.stars class+="input" %} </div> </div> <div class="field"> <label class="label">Review subject</label> <div class="control"> {% render_field form.subject class+="input" %} </div> </div> <div class="field"> <label class="label">Review text</label> <div class="control"> {% render_field form.text class+="textarea" placeholder="Review text" rows="10" %} </div> </div> <div class="field"> <label class="label">Username</label> <div class="control"> {% render_field form.author class+="input" placeholder="eg. ReviewerMan21, John Smith" %} </div> </div> <button type="submit" class="button">Add review</button> </form> My models.py: class Teacher(models.Model): grade = models.IntegerField() name = models.CharField(max_length=35) subject = models.CharField(max_length=50) ip = models.CharField(max_length=14) … -
Provide block to Django inclusion_tag
I have the following tag: @register.inclusion_tag('template.html') def my_field(field: BoundField): return {"field": field, "spam":42} html file: <span>{{ field }}</span> {{ spam }} But now I want to provide peace of HTML code to this tag: {% my_field field %} <b>I want this code to be displayed instead of spam </b> {% end_my_field %} For templates I can use blocks, but how can I do that for inclusion_tag? I can create custom compile function and create custom Node, but then inclusion_tag creates IncludeNode and I can't control it. -
Django ManyToOne?
I have an inventory management application, and inside is an Item() class that represents the product. All of the devices will be serialized so there will be a class later that represents each device called OnHand(). Item Model class Item(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100) manufacturer = models.ForeignKey('Manufacturer', blank=True, null=True, on_delete=models.SET_NULL) introduction = models.DateField(auto_now=True) quanity = models.IntegerField(default=0) is_retired = models.BooleanField(default=False) tags = models.ManyToManyField(Tag) def __str__(self): return self.name def add(self): pass def remove(self): pass def retire(self): # Rex came up with this, roll credits. pass def count(self): pass I want an attribute for on_hand that has a ManyToOne type relationship. OnHand Model Concept class OnHand(models.Model): name = models.CharFiled(max_length=100) serial = models.CharField(max_length=80) asset = models.CharField(max_length=20) def __str__(self): return self.serial When creating a new OnHand object, I'd like to associate it with the Item. How would I go about doing this? Structural Example Item Name = MacBook Pro Description = 15.5" MacBook Pro OnHand serial number, asset tag serial number, asset tag serial number, asset tag -
How to show / hide selected fields in a form within a formset?
Using django forms/formsets how do I construct a template that a user can toggle each rendered form in the formset to only display half of the form? For example each form has a true and a false set of inputs and the user will only want to see one set of inputs at a time (to avoid overloading the user and the view). The user would click on an image with an onclick to toggle between entering data for the true or false set of inputs. I can see how to do this without django forms but with them I'm a bit confused. Specifically, each field will have its own id that I would need to know in order to toggle the input type from text to hidden. class ExampleForm(forms.ModelForm): class Meta: model = Example fields = ( 'true_input01', 'true_input02', 'true_input03', 'true_input04', 'false_input01', 'false_input02', 'false_input03', 'false_input04', ) -
K8S Ingress and Rewrite
I am running django inside my minikube and I want to expose it. My pod is running both NGINX and Django with Gunicorn. I am also using the nginx ingress and I have managed to successfully do it with the following configuration: urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('api.urls')), ] ingress.yaml: apiVersion: extensions/v1beta1 kind: Ingress metadata: name: full-stack-ingress namespace: full-stack annotations: kubernetes.io/ingress.class: nginx nginx.ingress.kubernetes.io/rewrite-target: / spec: rules: - http: paths: - path: / backend: serviceName: django-service servicePort: 80 nginx.conf: upstream django { server 127.0.0.1:8000; } server { listen 80; location ~ /static/ { root /django/; } location / { proxy_pass http://django; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; proxy_redirect off; } } However, I want to change my ingress.yaml to use django-service using the /api path. Like this: spec: rules: - http: paths: - path: /api backend: serviceName: django-service servicePort: 80 But I did not managed to make this working even making changes in urls.py and my nginx.conf. I have also removed the "rewrite-target" and added a rewrite rule to nginx.conf but no success. What should I do to accomplish that? -
Django scheduled tasks
i want to display the current exchnage rate of USD/Bitcoin price-pair on my website. Therefor i set celery and a small periodic_task. Im currently not really able to understand how i call this periodic_task task or display the json data it returns. this is how my celeter setup look like: __init_.py from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ('celery_app',) celery.py from __future__ import absolute_import, unicode_literals from celery import Celery import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings') app = Celery('myproject') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) tasks.py from celery import Celery from celery.schedules import crontab from celery.task import periodic_task from celery.utils.log import get_task_logger import requests logger = get_task_logger(__name__) app = Celery('tasks', broker='redis://127.0.0.1') @app.task def test(): return "Test Successful" @periodic_task(run_every=(crontab(minute='*/15')), name="get_btc_exchange_rate", ignore_result=True) def get_exchange_rate(): api_url = "https://api.coinmarketcap.com/v1/ticker/?limit=1" try: exchange_rate = requests.get(api_url).json() logger.info("BTC Exchange rate updated.") except Exception as e: print(e) exchange_rate = dict() return exchange_rate I'm currently stating celery with this script: https://gist.github.com/psych0der/44a8994495abee1b4e832420c1c2974d So my question is how can i trigger that periodic_task and display the return of the json data/field "price_usd"? Thanks in advance -
Python Oracle - How to use 2 oracle clients
I need to run a django 2.1 project in a server that have an Oracle Client version 10. But when I try to runserver I get this error: Oracle client Library must be in version 11.2 or higher I did some research and the obvious solution was to update the Oracle. But I can't do that because the server runs some applications that only works with Oracle Client 10. One thing that I tought is to run two Oracle Library Clients. I did some research, one of the answers that I found: how to set oracle client library path in python when multiple oracle client version installed But, it's on Linux and I'm on a Windows Server 2012 R2. How could I run 2 of these Oracle Clients? Please, could you help me? -
Django - CreateView passing the created objects id to another CreateView
I've been trying to pass the values of a newly created object to the next CreateView so that a new child model can be created. This is what happens: User creates the Parent model through a CreateView If the form is valid the success_url redirects to the CreateView of another Child model. The child model in order to be created, needs the id of the Parent Model (ForeignKey relationship). Once the Child Model is created redirect to a completed page. Below I have an example of my code. class AddParentModelView(LoginRequiredMixin, CreateView): model = ParentModel template_name = "dashboard/add_parent_model.html" form_class = ParentModelForm success_url = '/REDIRECT_TO_CHILD_MODEL/' def form_valid(self, form): form.instance.owner = self.request.user # I Also tried sessions: # self.request.session['parent_id'] = form.instance.id # But they return None: # print(self.request.session["venue_id"]) return super().form_valid(form) class AddChildModelView(LoginRequiredMixin, CreateView): model = ChildModel template_name = "dashboard/add_child_model.html" form_class = ChildModelForm success_url = '/thanks/' What's the proper way to approach this? If possible, please explain your solutions. Thanks in advance! -
Django filter by Count annotated inside Subquery
Here is an abstract and simplified example. Say I want to get authors and annotate minimal count of books in category if it is greater than three. Book and Author models and are not connected with ForeignKey fields (remember, abstract and simplified, there is a reason): Author(models.Model): name = models.CharField(max_length=250) Book(models.Model): author_name = models.CharField(max_length=250) book_category = models.CharField(max_length=250) Here is simplest query I can get to reproduce: (Author.objects .annotate(min_valuable_count=Subquery( Book.objects .filter(author_name=OuterRef('name')) .annotate(cnt=Count('book_category')) .filter(cnt__gt=3) .order_by('cnt') .values('cnt')[:1], output_field=models.IntegerField() )) ) And I get an error: psycopg2.ProgrammingError: missing FROM-clause entry for table "U0" LINE 1: ... "core_author" GROUP BY "core_author"."id", "U0"."id" ... ^ Here is SQL: SELECT "core_author"."id", "core_author"."name", ( SELECT COUNT(U0."book_category") AS "cnt" FROM "core_book" U0 WHERE U0."id" = ("core_author"."chat_id") GROUP BY U0."id" HAVING COUNT(U0."book_category") > 3 ORDER BY "cnt" ASC LIMIT 1) AS "min_valuable_count" FROM "core_author" GROUP BY "core_author"."id", "U0"."id" -
Django ManyToManyField between 2 objects that point to one another
In my project, I have 2 models with a ManyToMany field that point to each other. In this case, I have Elections and Candidates. The idea is that an Election can have multiple Candidates and that a Candidate can also be part of multiple elections (One 'Candidate' is only one person). I have the following: project/elections/models.py from candidates.models import Candidate class Election(models.Model): candidates = models.ManyToManyField(Candidate) ... project/candidates/models.py from elections.models import Election elections = models.ManyToManyField(Election) ... When I try to run any command (makemigrations, runserver, etc.) I get a circular dependency between Election and Candidate which crashes. I have the models in different apps as a coding practice. Should I: Move both models to one app and one file Not have the models pointing to each other (how would I then accomplish my goal?) Do something different -
How to populate existing html form with djangos UpdateView?
I am trying to implement a simple UpdateView, but I want to use my own template. Using djangos auto_population is working, but not what I want, because I have lots of fields formatted differently. <form method="post" action="#"> {% csrf_token %} {{ form.as_p }} <input type="submit"> </form> But I want to use my own form template which looks like this: edit_template.html <form class="form-horizontal" role="form" method="POST" action="{% url 'update' pk=abc %}"> {% csrf_token %} <input name='varX' id="varX" type="text" placeholder="" class="form-class"> <input name='varY' id="varY" type="text" placeholder="" class="form-class"> </form> views.py class ModelUpdate(UpdateView): model = MyModel fields = ['varX','varY'] Now I would like that form to be populated with my object data, but the form is empty. UpdateView is also passing the data twice to the template: One as 'object' and one as 'mymodel'. I also tried updating get_context_data by adding context.update( model_to_dict(myModelData)) But that also does not change anything. How can I populate my custom form using djangos class-based views? -
Unable to load assets in Django
I have been reading up on the STATIC path function in Django but I still can't make my CSS & JS show up! Here is what I have in my settings: STATIC_URL = '/assets/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'assets'),] Here is the HTML calling the asset {% load static %} <link rel="stylesheet" href="{% static "bootstrap/css/bootstrap.min.css" %}"> I get this console error: And this is the tree I can see in the console Can anyone help me please? -
Dont work function clean for password in Django
i have Register form but why don't work function clean for password adn function clean_username: forms : class Register(forms.ModelForm): password = forms.CharField(widget=forms.TextInput(attrs={'type':'password', 'placeholder':'Password' , 'style' : 'font-size : 20px;color:white'}) , label = '') password2 = forms.CharField( widget=forms.TextInput(attrs={'type':'password', 'placeholder':'Confirm Password' , 'style' : 'font-size : 20px;color:white'}) , label = '') username = forms.CharField(label = '' , widget= forms.TextInput(attrs={'placeholder':'Username' , 'style' : 'font-size : 20px;color:white'})) number = forms.IntegerField(label = '' , widget= forms.NumberInput(attrs={ 'type' : 'number' , 'placeholder':'Number' , 'style' : 'font-size : 20px;color:white'})) country = forms.CharField(label = '' , widget= forms.TextInput(attrs={'placeholder':'Country' , 'style' : 'font-size : 20px;color:white'})) city = forms.CharField(label = '' , widget= forms.TextInput(attrs={'placeholder':'City' , 'style' : 'font-size : 20px;color:white'})) email = forms.EmailField(label = '' , widget= forms.EmailInput(attrs={'placeholder':'Email' , 'style' : 'font-size : 20px;color:white'})) age = forms.IntegerField(label = '' , widget= forms.NumberInput(attrs={'placeholder':'Age' , 'style' : 'font-size : 20px;color:white'})) class Meta: User = get_user_model() model = User fields = ('username', 'number', 'country', 'city', 'email', 'age', 'image') def clean_username(self): User = get_user_model() username = self.cleaned_data.get('username') qs = User.objects.filter(username=username) if qs.exists(): raise forms.ValidationError("username is taken") return username def clean(self): cleaned_data = super(Register, self).clean() password1 = self.cleaned_data.get("password") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return cleaned_data … -
Django Auth add placeholder in the login form
I was following this tutorial for Django login: https://wsvincent.com/django-user-authentication-tutorial-login-and-logout/ Here is what the code look like to enable login using django auth urls.py: from django.contrib import admin from django.urls import path, include from django.views.generic.base import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('customers/', include('django.contrib.auth.urls')),] and created a templates/registration/login.html template I want to add placeholder string in the login page for username and password. I tried subclassing the AuthenticationForm (suggested here: Django adding placeholders to django built in login forms) but I am not sure how to make the changes in the urls.py. I do not want to impact the other forms that come with the Django such as auth password_change etc. Note I am using Django 2.1.5 and python 3.6 -
Getting an error while building a register page, AttributeError at /register/ 'RegisterForm' object has no attribute 'cleaned_data'
I am building a registration page using Python 2.7.15 && Django 1.11.18, but continue to get the error: AttributeError at /register/ 'RegisterForm' object has no attribute 'cleaned_data' I've looked through other very similar posts, tried the suggestions, but still I am not getting a functional result. To me it looks like everything is in order, but it is not. Below you will find my code, thanks. Views.py looks like: def register_page(request): form = RegisterForm(request.POST or None) context = { "form": form } if form.is_valid(): form.save() print(form.cleaned_data) username = form.cleaned_data.get("username") email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") new_user = User.objects.create_user(username, email, password) print(new_user) return render(request, "auth/register.html", context) forms.py looks like: class RegisterForm(forms.Form): username = forms.CharField() email = forms.EmailField() password = forms.CharField(widget=forms.PasswordInput) password2 = forms.CharField(label='Confirm password', widget=forms.PasswordInput) def clean(self): data = self.cleaned_data password = self.cleaned_data.get('password') password2 = self.cleaned_data.get('password2') if password2 != password: raise forms.ValidationError("Passwords must match.") return data urls.py looks like: from django.conf.urls import url from django.contrib import admin from .views import home_page, about_page, contact_page, login_page, register_page urlpatterns = [ url(r'^$', home_page), url(r'^about/$', about_page), url(r'^contact/$', contact_page), url(r'^login/$', login_page), url(r'^register/$', register_page), url(r'^admin/', admin.site.urls), ] What am I missing here?