Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get form field values in class based form and send mail
Django version 2.2 I have a form as below in forms.py class NameForm(forms.Form): email_address = forms.EmailField(label='Your Email Address', max_length=100) in form.html <form method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> views.py class register(FormView): model = Student template_name = 'form.html' form_class = NameForm success_url = '../' def form_valid(self, form): return super().form_valid(form) models.py class Test(models.Model) email_address= models.EmailField(max_length=100) All the respective modules are successfully imported , and the form get submitted without any problems . What i need to do is , when a user provide an email address using the form, email address have to be checked with the email in the database(models.py) which is provided before . After checking with the emailaddresses in the database , if provided emailaddress matches the emailid in the database , email have to be sent to the email id . The logic is simple, but accessing and using the form.field values in class view form has failed . -
Django 1.11 - make the whole site read-only for users from a given group
Django 1.11 I have a group users who should have only read-only access to everything on the site. No restrictions on fields, models, and actial data, only what they can do with it (read-only). I know about possible implementations that suggest doing it "field-by-field" (or "make all fields read-only") and "model-by-model" solution. I am curios if there is a way to do it cleaner, on user group level, or at least on user level. -
How to make sense of documentation to model my django app and avoid most errors right from the start?
I'd like to get some opinions and/or feedback from your own experience as as a Django developer for this concrete question. Said more explicitly, can we not model a database without bugs or errors right from the start? How we prepare such a preparation task? Thanks. -
How to create a dynamic form with values in model using form.py?
I would like to create a dynamic form using forms.py where questions and answers come from values in the columns of models. I have three models, one called Sheet, which contains many questions from the Question model (Many to Many). The Question model can contain one or more answers from the Answer model (Many to Many) In my views.py, my function retrieves all values from Sheet model and sends values to my html file. In my html file I have a code that allows me to display all the questions with their answers. class Sheet(models.Model): form = models.ForeignKey(Form, on_delete=models.CASCADE) question = models.ManyToManyField(Question, blank=True) sheet_name = models.CharField(max_length=256) creation_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.sheet_name class Question(models.Model): is_parent = models.ManyToManyField("self", blank=True) answer = models.ManyToManyField(Answer, blank=True) in_french = models.TextField(max_length=512) in_english = models.TextField(max_length=512) def __str__(self): return self.in_french class Answer(models.Model): in_french = models.CharField(max_length=32) in_english = models.CharField(max_length=32) def __str__(self): return self.in_french {% for a_sheet in all_sheets %} <b>Survey: {{ a_sheet.sheet_name}}</b> {% for q in a_sheet.question.all %} <label>Question: {{ q.in_english }}</label><br/> <label>Answers:</label> {% if q.answer.all %} <select> {% for a in q.answer.all %} <option value={{ a.id }}> {{ a.in_french }} </option> {% endfor %} </select> {% else%} <input type="text" name="answer"> {% endif %} {% endfor %} {% … -
How to auto-fill fields while updating django forms?
I am creating a to-do app in django and while updating a task, i want to auto-fill the fields with previous data. Where am i messing up? This is my views.py for the same:- task = get_object_or_404(ToDoList, id=id) if request.method == "POST": form = UpdateTaskForm(request.POST) if form.is_valid(): task.description = form.cleaned_data['description'] task.save() form.save() return redirect(reverse('list')) else: form = UpdateTaskForm(instance=task) context = { 'form':form, 'task':task, } return render(request, 'TaskList/update.html', context) and this is my forms.py:- class Meta: model = ToDoList fields = ['title', 'description', 'due_date', 'completed'] -
how to fix "'gbk' codec can't decode byte 0xa6 in position 9737 " in django
when I write {% extends "base.html" %} in "home.html" and try to access '127.0.0.1:8000/hello',the server would throw an UnicodeDecodeError: 'gbk' codec can't decode byte 0xa6 in position 9737: illegal multibyte sequence and if I delete the extends sentences,that will not throw an Error. I don't know why System: Windows 10 Python: 3.7.2 Django: 2.2 home.html: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>test</title> </head> <body> {% extends "base.html" %} {% block mainbody %} <p>extends base.html 文件</p> {% endblock %} </body> </html> base.html: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>testing</title> </head> <body> <h1>Hello World!</h1> <p> Django test.</p> {% block mainbody %} <p>original</p> {% endblock %} </body> </html> -
How fix error in Django templates/base.py?
I am trying to install Django 2.8 on Ubuntu 16.04 and I get an error from Django. I have no idea how to solve problem in the internal files of Django. $ sudo django-admin startproject --template=https://github.com/GeoNode/geonode/archive/2.8.x.zip -e py,rst,json,yml my_geonode6 Traceback (most recent call last): File "/usr/local/bin/django-admin", line 5, in <module> management.execute_from_command_line() -------------------------------------------- File "/home/gislab/Envs/geonode/local/lib/python2.7/site-packages/django/template/base.py", line 387, in empty_variable raise self.error(token, "Empty variable tag") django.template.base.TemplateSyntaxError: Empty variable tag -
how to fix list index out of range error while importing large csv file
Here is part of the code below. I'm just blank about how it isn't working. I have been working on django,but while importing a csv file which contains 9500 records there is in error list index out of range. And as the result only 500-600 records are loaded in database. when I re-import the csv file the number of records submitted keeps on changing. However the complete file is not yet had been uploaded.enter image description here -
My cart view is no longer adding products after introducing inline formset to django admin
I've been learning django (version 2.1) through "Django by Example" by Antonio Mele, and I'm in the process of extending the online shop example. I thought it necessary to add attributes for products, and given that list of attributes, say color or size, may differ for products I added an attributes model and linked it to the admin (no problem there). However in trying to implement changes to the cart form, product detail and cart detail view, only one product is allowed to be added. If removed, nothing else gets added until a new session is triggered by logging out and in again. I'm not exactly sure about what I'm missing when introducing the changes. Before introducing the product attributes here are the code snippets of when things were working right. The shop models.py class Category(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, unique=True) class SubCategory(models.Model): name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, unique=True) category = models.ForeignKey(Category, related_name='subcat', on_delete=models.CASCADE) class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) sub_category = models.ForeignKey(SubCategory, related_name='prodsubcat', blank=True, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True, help_text='Product name') slug = models.SlugField(max_length=200, db_index=True, unique=True) description = models.TextField(blank=True) price = models.DecimalField(max_digits=20, decimal_places=2) available = models.BooleanField(default=True) stock = models.IntegerField(default=10) ...#And a bunch … -
how can I change the value of a booleanfield from static file using checkboxes
I've just started using django and I'm not so familiar with it. This is my problem, I simply want to tick a checkbox and change the value of a booleanfield in the model which is default=false to true I'm trying to create a function from views.py, but if there is any way to do it directly from the static file where my checkbox is that would do the work for me either This is my views.py def check(request): check = AddToCart.objects.get(orderd = request.GET['orderd']) check.is_active = True check.save() This is the checkbox Check: <input type="checkbox" name="checked" value="checked"> This is my model on models.py: class AddToCart(models.Model): id = models.AutoField(primary_key=True, unique=True) id_product = models.ForeignKey(Produkte, on_delete = models.DO_NOTHING) quantity = models.IntegerField() id_user = models.ForeignKey(User, on_delete = models.DO_NOTHING) orderd = models.BooleanField(default=False) @property def cmimi_total(self): return self.quantity * self.id_product.cmimi I have some objects inside AddToCart and I want to change the boolean values of each of them to True when the checkbox is ticked. I know my problem is just a basic one but as a newbie i could use some help. Thank You ! -
How to use form_validate() with CustomForm in Django
I'm creating an app in which I'd like to use my own custom login form with a captcha field. My intention is to do this without using an external library (except for requests) but I couldn't add captcha field to my custom form in forms.py, so I added it directly to login.html but for some reason when I do form.is_valid() it returns an error. I've already seen the solutions in Django - adding google recaptcha v2 to login form and Adding a Recaptcha form to my Django login page but as I said, I'd like to do this without using an external library. views.py ... def login_view(request): if request.method == 'POST': form = CustomLoginForm(request.POST) result = is_recaptcha_valid(request) print(result) # prints True if form.is_valid(): username = form.cleaned_data['username'] email = form.cleaned_data['email'] password = form.cleaned_data['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Redirect to index messages.success(request, "Logged in.") return HttpResponseRedirect(reverse('orders:index')) else: messages.error(request, "Invalid credentials.") else: print("error") return render(request, 'registration/login.html', {'form': CustomLoginForm()}) else: form = CustomLoginForm() return render(request, 'registration/login.html', {'form': form}) forms.py class CustomLoginForm(AuthenticationForm): email = forms.EmailField( error_messages={ 'required': 'Please enter your email.', 'invalid': 'Enter a valid email address.' }, help_text='Email', ) login.html <form class="" action="{% url 'orders:login' … -
Why testing doesn't detect test.py's syntax errors? and help me fix a bug
I wrote a test code as below and it has some bugs, which I can't detect but my teacher said you have missed self somewhere in your code. That was like a hint that I couldn't find that. This is my code: def HomeTests(TestCase): def setUp(self): board = Board.objects.create( title='Django', description='Django Desc') url = reverse('home') response = self.client.get(url) def home_test_view_status_code(self): self.assertEqual(response.status_code, 200) def home_test_func(self): view = resolve('/') self.assertEqual(view.func, home) def test_home_contains_link_to_topics_page(self): board_topics_url = reverse( 'board_topics', kwargs={'id': board.pk}) self.assertContains(response, 'href={0}'.format(board_topics_url)) Even if I run python manage.py test this code doesn't throw any error: System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s please help me what I am doing wrong here. where should be self keyword? and why? Then, I went to library and checked to find the bug and by mistake I added a 'p' in view = resolvep('/') and without knowing I run python manage.py test it showed this result: C:\Users\Administrator\Desktop\Practice\board\src>python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK Destroying test database for alias 'default'... while checking back my code I saw I misspelt resolve, here I come upon this question … -
Django test db connection not closed
I use Selenium to test that a language switcher on a Django site behaves properly. For internationalization I use Djangos build in capabilities. The tests pass fine, but right after they finish, I get a psycopg2.OperationalError saying that there is one other session using the database. The tests aren't actually using the database, from what I can see only djangos session management is. Setting SESSION_EXPIRE_AT_BROWSER_CLOSE to True doesn't help, even though I call driver.quit() in the tearDownCLass method of the test. Closing all connections through connections.close_all() changes nothing as well. select * from pg_stat_activity while running the test shows that there is indeed a idle connection open in the COMMIT stage while the test database is being dropped. I can work around that issue by defining a DiscoverRunner that skips teardown_databases, but that's an ugly solution at best. -
Django filter __date with timezone aware
Assume I am using Django 2.x and use default settings. i.e, TIME_ZONE = 'UTC' and USE_TZ = True I am recording data in Honolulu, Hawaii, which means 2019-4-9 9pm (user time) in Honolulu is 2019-4-10 in UTC (server time) Now I want to fetch the data by date 2019-4-9 in Honolulu time (user time) Here is what a demo code class TimelineTable(models.Model): accessed = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.accessed}' Here is the data in TimelineTable ID accessed 1 2019-04-10 07:19:30.319881 2 2019-04-10 07:19:35.004506 3 2019-04-10 07:19:37.612088 Without considering timezone, fetch data works fine >>> TimelineTable.objects.filter(accessed__date=datetime.date(2019, 4, 9)) <QuerySet []> >>> TimelineTable.objects.filter(accessed__date=datetime.date(2019, 4, 10)) <QuerySet [<TimelineTable: 2019-04-10 07:19:30.319881+00:00>, <TimelineTable: 2019-04-10 07:19:35.004506+00:00>, <TimelineTable: 2019-04-10 07:19:37.612088+00:00>]> Now the problem is with timezone. I am talking to server: Hey, give me those entries I recorded in 2019-4-9 at Honolulu. >>> Honolulu = pytz.timezone("Pacific/Honolulu") >>> t = datetime.datetime(2019, 4, 9, tzinfo=Honolulu) >>> TimelineTable.objects.filter(accessed__date=t) <QuerySet []> I expected 3 entries, but nothing happens. How to get these entries, without any bugs? -
Create and Edit buttons for ParentalKey/ForeignKey
Is it possible to show "add" and "edit" buttons to wagtail admin panel as implemented in django admin panel? enter image description here -
Restart the Django Server after DB change
How can I make the Django server restart everytime I changed something in the database? So let's say I executed a Model.objects.update() on the DB, how can I make the Django server do a restart automatically? Any help would be appreciated. -
Returning current user information with responses in django-restframework api calls
Basically, I have an api that allows a user to create a profile and create posts and add friends. I wanted to know how I can handle the current user information so that I can store on the frontend which is in vue.js and make sure that the data is not stale and always updated. I wanted to avoid making a separate api call for retrieving the current user info. How can I achieve this? I have class based views and am using token authentication using django-rest-auth. -
how to fix this error from templates in django
i wrote the polls project by django but there is a problem : Reverse for 'vote' with arguments '('',)' not found. 1 pattern(s) tried: ['polls/(?P<pk>[0-9]+)/vote$'] my vote view is like this : def vote(request, pk): question = get_object_or_404(Question, pk=pk) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.vote += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) and this is detail.html : <h1>{{question.text}}</h1> {% if error_message %}<p><strong>{{error_message}}</strong></p>{% endif %} <form action="{% url 'polls:vote' question.id %} " method="post"> {% csrf_token %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> <label for="choice{{ forloop.counter }}">{{ choice.text }}</label><br /> {% endfor %} <input type="submit" value="vote"/> </form> i have tried this but it does not answered : <form action="{{question.id}}/vote}}" method="post"> -
Django JSONField does not save 0 value
I have a JSONField in my model, when I try to save 0 as value in json in django admin page, it saves value as null. How can I save zero as value? my JSONField: lecturer_scores = JSONField( verbose_name=_("Lecturer Score"), validators=[validate_lecturer_score], default=dict, blank=True ) My input: { "score 1": 0, "score 2": 5 } it saves like: { "score 1": null, "score 2": 5 } -
How to Map table views of a legacy Database in Oracle to django models?
I am working on a project that requires connecting to an existing remote Oracle database. the problem is that the client has not given full access to the database. instead i'm only given accesss to some views(Relational Database View) of the database. the table names are not provided. I'm able to perfrom raw sql queries to the legacydb in my django view. But it would be very much more easier if i could generate the models for these views and use django ORM. is there any way to accomplish this? -
KeyError at - request - django templatetag
Here is my code in template tag @register.simple_tag(takes_context=True, name=CAR_TEMPLATE_TAG_NAME) def g_c(context,session_key=None,c_class=Car): request = context['request'] return c_class(request, session_key=session_key) In the template it is used as {% g_c as car %} and the issue is keyerror 'request' at request = context['request'] -
How to display triple nested dictionary values in a Django template?
I have a list of dictionaries produced by a raw django query and a custom sorting algorithm: ordered_list = [{'qmaLevel': Decimal('1'), 'materials': None, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': '12U x 600 x 650 Professional Rack ', 'qmaQuoteAssemblyID': 0, 'qmaPartID': 'RACK S9 ', 'quantity': Decimal('1.00000'), 'qmaParentAssemblyID': 0}, {'qmaLevel': Decimal('2'), 'indent': '____', 'materials': None, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': '. ', 'qmaQuoteAssemblyID': 1, 'qmaPartID': 'COLOUR ', 'quantity': 1.0, 'qmaParentAssemblyID': 0}, {'qmaLevel': Decimal('3'), 'indent': '________', 'materials': None, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': 'Colour: Mannex Suede ', 'qmaQuoteAssemblyID': 21, 'qmaPartID': '800-560192 ', 'quantity': 1.0, 'qmaParentAssemblyID': 1}, {'qmaLevel': Decimal('2'), 'indent': '____', 'materials': None, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': '. ', 'qmaQuoteAssemblyID': 2, 'qmaPartID': 'FRAME ', 'quantity': 1.0, 'qmaParentAssemblyID': 0}, {'qmaLevel': Decimal('3'), 'indent': '________', 'materials': {1: {'qmmPartID': '128114 ', 'qmmPartShortDescription': '1.30;300;200;Black/White;Acrylic;Label; ', 'imrWeight': Decimal('0.00000')}, 2: {'qmmPartID': '800-560271 ', 'qmmPartShortDescription': 'Rivet;Alum;Truss;4.0;8.7; ', 'imrWeight': Decimal('0.00149')}, 3: {'qmmPartID': '800-560350 ', 'qmmPartShortDescription': 'Key;Ring;20mm; ', 'imrWeight': Decimal('0.00000')}}, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': 'Label 19" Rack Container Commercial ', 'qmaQuoteAssemblyID': 22, 'qmaPartID': '1A000 ', 'quantity': 1.0, 'qmaParentAssemblyID': 2}, {'qmaLevel': Decimal('3'), 'indent': '________', 'materials': {1: {'qmmPartID': '800-560008 ', 'qmmPartShortDescription': 'Colour;Powdercoat;General;Production Use ', 'imrWeight': Decimal('1.00000')}, 2: {'qmmPartID': '124632 ', 'qmmPartShortDescription': '1.90;M2;ZAN; ', 'imrWeight': Decimal('14.91500')}}, 'qmaQuantityPerParent': Decimal('1.00000'), 'qmaPartShortDescription': 'Frame Top x 600 x 650 Typ 0P ', 'qmaQuoteAssemblyID': 23, 'qmaPartID': '0R000P ', 'quantity': 1.0, 'qmaParentAssemblyID': … -
Celery Task needs to run every N time but need to finish first
so i am using django + celery(rabbitMQ). I wrote several tasks for download files, and send request to notify "hey, i got the file" response. I want to run these tasks run in parallel. Hence i used, celery's group and chain combo. Now the main problem, when i run task it works and all the tasks were called and i just can't detect whether all tasks finished or not. Is it possible to know that all the relevant tasks finished? PS:// I thought using celery beat does not suit for this job. Because current tasks might not done when celery beat executes. Here is my snippet, i call this task at first. @shared_task(name="getOrders", bind=True, retry_backoff=10, autoretry_for=(exceptions.RequestException,), retry_kwargs={"max_retries": 3, "countdown": 5}) def getOrders(self): url = "https://example.com/orders" orders = fetchData(url) # fetch function if orders.status_code == requests.codes.ok: tree = etree.fromstring(orders.content) jobs = group([download_order.si(order_id) for order_id in tree.xpath('order/text()')]) chain(jobs, notify.s()).apply_async() self.retry(countdown=900, max_retries=2) download task is: @shared_task(name="download_order", acks_late=True, autoretry_for=(exceptions.RequestException,), retry_kwargs={"max_retries": 3, "countdown": 5},) def download_order(order_id): """Download order""" print("\n===========\nstarting download on {}\n=========\n".format(order_id)) url = "https://example.com/order/{}.xml".format(order_id) get_xml = fetchData(url) if fulfillment_request.status_code == request.codes.ok: print("\n=======\nxml fetched\n========\n") tree = etree.fromstring(get_xml.content) for product in find_product(tree): uuid = product.find("UUID").text for v in product.iterfind("product"): file_type = "Video" file_id = v.find('files/file/id').text url … -
Problem in displaying different chart types using drildown in fusioncharts
I want to display the parent chart in bar2d and the child chart in pie2d. But I am able to render both the parent and child charts in the same type. Also I used configureLink() method to specify my child chart type. But it is throwing an error like 'str' object has no attribute 'configureLink'. The code that I have tried is: Views.py def drilldown(request): drilldownobj = FusionCharts( 'column2d', 'chart-container', '600', '400', 'drilldown-chart', 'json', {"chart": { "caption": "North American Population", "subcaption": "USA & Canada", "xaxisname": "Country (Click to drill down)", "theme": "fusion" }, "data": [ { "label": "United States", "value": "310380000", "link": "newchart-json-usa" }, { "label": "Canada", "value": "34020000", "link": "newchart-json-can" } ], "linkeddata": [ { "id": "usa", "linkedchart":{ "chart": { "caption": "Population by Religion", "subcaption": "USA", "showpercentintooltip": "1", "enablemultislicing": "0", "startingangle": "90", "theme": "fusion" }, "data": [ { "label": "Christian", "value": "78.30" }, { "label": "Muslim", "value": "0.90 " }, { "label": "Hindu", "value": ".60" }, { "label": "Buddhist", "value": "1.20" }, { "label": "Jewish", "value": "1.80" }, { "label": "Others", "value": "17.20" } ] } }, { "id": "can", # "type":"pie2d", "linkedchart": { "chart": { "caption": "Population by Religion", "subcaption": "Canada", "showpercentintooltip": "1", "startingangle": "90", "theme": "fusion" }, … -
pycharm django debug configrations doesn't recognize apps folder
All my apps are in apps folder I also added sys.path.insert(0, os.path.join(BASE_DIR, "apps")) in settings.py my project structure as below: But when I simply create and run a default Django Server in Pycharm (2019.1) It returned error '... 'apps' is not a package' My project runs perfectly in pipenv shell; python manage.py runserver Can anyone help me, please?