Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to select data from a query set and pass it to the same page to perform an insert in a database with django
I try to implement sort of a simple sales app in my django webpage, I try to select some data from a filter I implemented from this video video, I need to add select buttons infront of the element and a button to add. This is what I want to implement image, after I select one element and press ADD, then the element should be added in the second block and then when I press finish then it should be added to my database. The table where i should the products is model with the following code class Product(models.Model): name = models.TextField(blank=False, max_length=25) brand = models.TextField(blank=False, max_length=25) price = models.PositiveSmallIntegerField(default=200) I know how to login and start session. So I would like to add from the second block (like in the image) with the button finish to a table defined with: class Sale(models.Model): user = models.TextField(blank=False, max_length=25) # The current log in user product = models.ForeignKey(Product, on_delete=models.CASCADE) price = models.PositiveSmallIntegerField(default=200) # The price This is for personal use, so it don't matter that is not bootstrap or look badly. Preferably I would like to know if there is a tecnique to do this and how is called or if I … -
UnboundLocalError: local variable 'team_members' referenced before assignment
i am getting below error UnboundLocalError: local variable 'team_members' referenced before assignment slug values in model by default are 1 . This is the function def single_slug(request, single_slug): team = [c.infraTeam_slug for c in infraTeam.objects.all()] if single_slug in team: team_members = TeamMember.objects.filter(infra_team__infraTeam_slug=single_slug) series_urls = {} for m in team_members.all(): part_one = vulnerability.objects.filter(member_name__member_name=m.member_name).earliest("vulnerabilty_date") series_urls[m] = part_one.vulnerability_slug return render(request=request, template_name='main/category.html', context={"member_name": team_members, "part_ones": series_urls}) Please help how cann i solve this problem -
Run a python script just after run server django
I have a python script with indefinite loop it keeps in checking for the data, now I am confused how do I execute it so that it keeps running if the server is running. I think the script should run just after I run server in django but how do I run this script? Any suggestions? -
How can I exclude an object from my model?
I need to exclude 1 size from my model Good with field: Size = models.ManyToManyField('Size') Size model: class Size(models.Model): size = models.CharField(max_length = 15) def __str__(self): return self.size I try do this in views.py: good1 = Good.objects.get(id = good_id) choosen_good_size = good1.Size.get(size = 'XS') choosen_good_size.exclude() good1.save() But I get an error: Exception Value: 'Size' object has no attribute 'exclude' In another cases I get AttributeError: Manager isn't accessible via Good instances What should I do to make it works? -
How to change column name and alignment
Hi I am using TabluarInLine in my Django ModelAdmin. How can I rename DELETE? column, and center those checkboxes in the cell (I want them and delete column to create a line). -
TypeError: string indices must be integers When Checking array with dictionaries
When checking if a key with certain value exist, I get a Type Error: string indices must be integers. if not any(dObj["date"] == wholeDay for dObj in userPunchCard.clock): status = "Clock In" content = { "name" : user.name, "title" : user.title, "status" : status } This is the db for userPunchCard class StaffMember(models.Models): name = models.CharField(max_length = 255) title = models.CharField(max_length = 255) email = models.ChardField(max_length = 255) password = models.ChardField(max_length = 255) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) objects = UserManager() class PunchCard(models.Model): clock = models.CharField(max_length = 9999) employee = models.ForeignKey(StaffMember, on_delete=models.PROTECT) I'm positive that userPunchCard.clock is indeed an array with at least one dictionary present because of this code. if userPunchCard.clock is None: print ("if was hit in dashboard") else: if not any(dObj["date"] == wholeDay for dObj in userPunchCard.clock: status = "Clock In" content = { "name" : user.name, "title" : user.title, "status" : status } When Creating a Django db table, the table will have null when empty and None works for me all the time to check for it. So the else in this code is running instead of the if. Also, when a user does clock in, this is the code … -
Annotating with aggregation from another model
I have 4 models class SingleDonation(models.Model): name = models.CharField( max_length=255, ) email = models.EmailField() transaction = models.OneToOneField(Transaction) class RecurringDonation(models.Model): name = models.CharField( max_length=255, ) email = models.EmailField() subscription = models.OneToOneField(Subscription) class Subscription(models.Model): raw_amount = models.PositiveIntegerField() interval = models.CharField( max_length=10, ) class Transaction(models.Model): raw_amount = models.PositiveIntegerField() subscription = models.ForeignKey( to=Subscription, on_delete=models.SET_NULL, null=True, blank=True ) I'm trying to annotate both Donations querysets with the total amount donated by the email to get the correct amount for API for let's say SingleDonation, I do it in serializer this way def get_transaction_sum_for_email(self, obj): single_donation_sum = SingleDonation.objects.filter(email=obj.email).aggregate(Sum('transaction__raw_amount')).get('transaction__raw_amount__sum') recuring_donation_sum = RecurringDonation.objects.filter(email=obj.email).annotate(transaction_sum=Sum('subscription__transaction__raw_amount')).aggregate(Sum('transaction_sum')).get('transaction_sum__sum') or 0 return single_donation_sum + recuring_donation_sum Yet I want to order_by() this amount, so I have to annotate my queryset with this number, and this is where I have a problem. How do I do it? -
Django Pagination Error. Which object to use as page_obj?
I am trying to make a quiz where each question will be displayed on a different page. But I guess attributes like has_previous and has_next are not working. views.py def instructions(request): ques = Questionm.objects.first() context = {'ques': ques} return render(request,'events/instructions.html', context) def ques_detail(request,pk=Questionm.objects.filter(marks=10).order_by("pk").values().first()): ques = get_object_or_404(Questionm, pk=pk) context = {'ques': ques} paginate_by = 1 return render(request, 'events/ques_detail.html', context) def ques_detail2(request, pk): ques = get_object_or_404(Questioni, pk=pk) context = {'ques': ques} paginate_by = 1 return render(request, 'events/ques_detail2.html', context) ques_detail.html {% block title %} <div class="round1"> <h1>ROUND-1</h1> </div> <div class="ques"> <h2>Q. {{ ques.question }}</h2><br><br><br><br> <p><input type="checkbox" name="opt1">{{ ques.opt1 }}<br><br> <input type="checkbox" name="opt2">{{ ques.opt2 }}<br><br> <input type="checkbox" name="opt3">{{ ques.opt3 }}<br><br> <input type="checkbox" name="opt4">{{ ques.opt4 }}<br><br></p> <div class="pagination"> {% if is_paginated %} {% if ques.has_previous %} <a class="btn btn-outline-info mb-4" href="?page={{ ques.previous_page_number }}">Previous</a> {% endif %} {% for num in ques.paginator.page_range %} {% if ques.number == num %} <a class="btn btn-info mb-4" href="?page={{ num }}">{{ num }}</a> {% endif %} {% endfor %} {% if ques.has_next %} <a class="btn btn-outline-info mb-4" href="?page={{ ques.next_page_number }}">Next</a> {% endif %} {% endif %} </div> </div> {% endblock %} I am just able to see question and four options. Not the previous and next buttons. Someone kindly help. -
How to setup django shell kernel for jupyter notebook running in separate docker containers
I have several Django projects, each running in a docker container (each one having its own) on a single machine. I want to setup a Jupyter Notebook in a new container, and be able to have kernels for all these django projects (kernels that use their shell and environment). Any ideas? I came across this answer but this can only be used for when the django project and the jupyter notebook are running on the container :( -
How can I combine bootstrap cards with lightbox?
I have a page where users will be able to upload many images and view them in the page with other data so i wanted to use Bootstrap cards under the other data and combine lightbox with bootstrap. Here's the code I wan to make a for loop to repeat it. <div class="row"> <div class="col-md-4"> <div class="card mb-4 shadow-sm"> <svg class="bd-placeholder-img card-img-top" width="100%" height="225" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMidYMid slice" focusable="false" role="img" aria-label="Placeholder: Thumbnail"><title>Placeholder</title><rect width="100%" height="100%" fill="#55595c"/><text x="50%" y="50%" fill="#eceeef" dy=".3em">Thumbnail</text></svg> <div class="card-body"> <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <button type="button" class="btn btn-sm btn-outline-secondary">View</button> <button type="button" class="btn btn-sm btn-outline-secondary">Edit</button> </div> </div> </div> </div> </div> </div> I tried this : <div class="row"> <div class="col-md-12"> <div class="mdb-lightbox"> {% for image in Patient_detail.images.all %} <figure class="col-md-4"> <img alt="picture" src="{{ Patient.UploadedImages.pre_analysed.url }}" class="img-fluid img-thumbnail"> <form method="POST" action="{% url 'patients:image_delete' image.pk %}"> {% csrf_token %} <div class="card-body"> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <!-- <button type="button" class="btn btn-sm btn-outline-secondary">Analyse</button> --> <button type="submit" class="btn btn-sm btn-outline-secondary">delete</button> </div> </div> </div> </form> </figure> {% endfor %} </div> </div> </div> The images Number is shown (places for the … -
How can I use exclude or filter with CharField?
I have a Good model with this Field: Size = models.ManyToManyField('Size') And Size model: class Size(models.Model): size = models.CharField(max_length = 15) def __str__(self): return self.size In views.py I need to exclude 1 size, so I try: good1 = Good.objects.get(id = good_id) good1.Size.exclude(size = 'XS') But exclude doesn't work... I think it's because of impossibility to compare size field with string 'XS' How can I fix it? -
How to set correct path in anchor tag
I'm working on a simple Django app. Right now I can link different pages via anchor tags using href="{ url 'name'} which I believe is the "Django way to do things". The problem is that as soon as I try to link a file that exists in a different location, I get an error. I've tried changing the name, function, and path, but I'm stuck. The errors vary, but it's usually related to trying to find pyoop.html in the wrong location. The only difference really is the pyoop.html is inside an "extra folder" which is not the case for the other files. # views.py def pyoop(request): return render(request, 'book/pages/pyoop.html') #urls.py urlpatterns = [ ... path('py-oop/', views.pyoop, name="book-pyoop") ] #index.html <a href="{ url 'book-python-oop'}">Link to Python-oop</a> pyoop.html is the only file inside the 'pages' folder, everything else is inside the 'book' folder. -
django static file : The requested resource was not found on this server
my html <!DOCTYPE html> {% load static %} <html> <head> <title>Fish store</title> <link rel="stylesheet" type="text/css" href="{% static 'css/animate.css' %}"> </head> <body> <h2>Home page</h2> </body> </html> my settings.py INSTALLED_APPS = [ 'fish.apps.FishConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] in fish app I have static folder and css folder, and then animate.css fish/static/css/animate.css main url urlpatterns = [ path('admin/', admin.site.urls), path('',views.index) ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Now I try to access http://localhost:8000/static/css/animate.css it shows: Not Found The requested resource was not found on this server. -
Django not uploading staticfiles to Amazon S3
I am trying to upload my static files onto Amazon S3 but it is still collecting the static files on a local folder. Any idea of how I can get my Django collectstatic to upload onto S3? Here are the relevant code bits: Using Boto and django-storages. The undesired behavior (0 static files copied since I just ran it): > python manage.py collectstatic > 0 static files copied to '/Users/michaelninh/PycharmProjects/Collab/staticfiles', 132 unmodified, 292 post-processed. Installed Apps: 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'django.contrib.sites', # third party 'allauth', 'allauth.socialaccount', 'allauth.account', 'multiselectfield', 'easy_thumbnails', 'image_cropping', 'storages', # first party 'user.apps.UserConfig', 'profiles.apps.ProfilesConfig' ] Connection to S3 AWS_ACCESS_KEY_ID = 'XXX' AWS_SECRET_ACCESS_KEY = 'YYY' AWS_STORAGE_BUCKET_NAME = 'ZZZ' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')``` -
Optimizing Django REST Framework queries using prefetch_related
I'm not quite understanding the concept of prefetch_related for optimizing the related_name queries. However I seem to be in much need of it at this moment. I wish to optimize the following queryset as I have a bunch of similar looking queries: return Customer.objects.filter( Q(company__administrators__user=user) | Q(company__employees__employee_roles__user=user, company__employees__employee_roles__group__permissions=40) | Q(projects__project_roles__user=user, projects__project_roles__group__permissions=40, access='Restricted') | Q(projects__schedules__schedule_roles__user=user, projects__schedules__schedule_roles__group__permissions=40, projects__access='Restricted', access='Restricted') | Q(customer_roles__user=user, customer_roles__group__permissions=40) ).distinct() What would be the optimal way to do this using prefetching? Currently this query takes about 10 seconds on the development server, compared to < 1 second when returning Customer.objects.all(). Thus I have figured it boils down to the query and not serialization of the data. -
Creating input view for many to 1 relationship in Django
I'm attempting to create a page where users can input a recipe. Users would need to name the recipe, then input a list of ingredients and steps to follow during the recipe. I've set up 4 models Recipe - stores the name as well as the user inputing the recipe Ingredients - stores all ingredients possible (with potential to add new ingredients) Recipe_Ingredients - pairs unlimited number of ingredients to a recipe Step - allows user to enter an unlimited number of steps for a recipe I'm able to input recipes through the admin page, however this is: A. clunky B. doesn't allow non-admins to enter new recipes from django.db import models from django.contrib.auth.models import User # Create your models here. class Ingredient(models.Model): name = models.CharField(max_length=500, blank=False, null=False) link = models.CharField(max_length=500, blank=True, null=True) def __str__(self): return self.name class Recipe(models.Model): title = models.CharField(max_length=250, blank=False, null=False) notes = models.TextField(blank=True, null=True) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title class Recipe_Ingredient(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) unit = models.ForeignKey(Unit, on_delete=models.CASCADE, blank=True, null=True) amount = models.DecimalField(decimal_places=3, max_digits=10000) class Step(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) step_number = models.IntegerField(default=1) step = models.TextField(blank=True, null=True) def __str__(self): return self.step I'm hoping to create a page where … -
Cannot overwrite attachment values DATABASE_URL
How do i change the database_url in heroku for my django app? heroku addons:detach DATABASE -a is not working -
I have trouble finding the site
I do a search for articles on the site. Filtering should be by article title. Data from the search should be displayed in the template/ I tried to filter the data using order_by and filter views.py def post_search(request): form = SearchForm() if 'query' in request.GET: form = SearchForm(request.GET) search = request.GET['username'] if form.is_valid(): cd = form.cleaned_data results = SearchQuerySet().models(Articles).filter(content=cd['query']).load_all() total_results = results.count() return render(request, 'news/posts.html', {'form': form, 'search': search, 'cd': cd, 'results': results, 'total_results': total_results}) posts.html {% if "query" in request.GET %} <h1>Posts containing "{{ cd.query }}"</h1> <h3>Found {{ total_results }} result{{ total_results|pluralize }}</h3> {% for result in results %} {% with post=result.object %} <h4><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h4> {{ post.body|truncatewords:5 }} {% endwith %} {% empty %} <p>There are no results for your query.</p> {% endfor %} <p><a href="{% url 'post_search' %}">Search again</a></p> {% else %} <h1>Search for posts</h1> <form action="{% url 'post_search' %}" method="get"> <h3>Search</h3><input style=" border: 3px solid #4242A3; border-radius: 15px ; " type="text" name="search" value=" searchк "> <br> <input type="submit" value="Search"> </form> {% endif %} urls.py path('search/', views.post_search, name='post_search'), models.py class Articles(models.Model): title = models.CharField(max_length= 200) post = models.TextField() date = models.DateTimeField() img = models.ImageField(upload_to='', default="default_value") tags = TaggableManager() article_like = models.IntegerField(default='0') article_dislike = models.IntegerField(default='0') … -
Make required False in django graphene with relay
Django-Graphene with relay makes id required to get an object, I want to make required=False on my Node, so I can get the node by the logged in user instead of the user ID class Customer(models.Model): user = models.OneToOneField(User) class CustomerNode(DjangoObjectType): class Meta: model = Customer interfaces = (graphene.relay.Node,) @classmethod @login_required def get_queryset(cls, queryset, info): # This will work return queryset.get(user=info.context.user) class Query(graphene.ObjectType): customer = graphene.relay.Node.Field(CustomerNode) all_customers = DjangoFilterConnectionField(CustomerNode) query getCustomer { customer(id: "XXX") { # I don't want to pass this parameter! id } } -
Getting same thread id inside celery workers
I tried getting the current thread id and process id while running a task inside a celery worker process. I have set prefetch multiplier to 1 and I have 4 cpu core machine, so there will be 4 worker processes running for each workers. I have only 1 worker running ( 4 worker processes). As per my understanding each of the worker processes actually handles the execution of task. When I run 4 tasks simultaneously I tried getting the process id and thread id inside the task using os.getpid() and threading.get_ident() respectively. To no surprise, for every task running I got the same set of 4 process_id (as there are 4 worker processes running), but the thread id for each of the process are same. I am not able to understand how is this possible. Following is my observations when running tasks: > log: pid id: 513, t_id 140373758563328 > log: pid id: 514, t_id 140373758563328 > log: pid id: 513, t_id 140373758563328 > log: pid id: 513, t_id 140373758563328 > log: pid id: 513, t_id 140373758563328 > log: pid id: 513, t_id 140373758563328 > log: pid id: 578, t_id 140280371217408 > log: pid id: 579, t_id 140280371217408 -
django.core.exceptions.FieldError: Local field 'email' in class 'User' clashes with field of similar name from base class 'AbstractUser'
I created a AbstractUser class in my reg_group app's models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.html import escape, mark_safe class User(AbstractUser): is_client = models.BooleanField(default=False) is_agency = models.BooleanField(default=False) is_vendor = models.BooleanField(default=False) email = models.EmailField(max_length=255, default=None, blank=True, null=True) class User_Info(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) def __str__(self): return self.user.name I also have another app notification whose models.py is such: from django.db import models from swampdragon.models import SelfPublishModel from .serializers import NotificationSerializer class Notification(SelfPublishModel, models.Model): serializer_class = NotificationSerializer message = models.TextField() When i run python manage.py runserver i get the error django.core.exceptions.FieldError: Local field 'email' in class 'User' clashes with field of similar name from base class 'AbstractUser' But there is no email field in notification database. The raw code of database is such : CREATE TABLE "notifications_notification" ( "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "level" varchar(20) NOT NULL, "actor_object_id" varchar(255) NOT NULL, "verb" varchar(255) NOT NULL, "description" text, "target_object_id" varchar(255), "action_object_object_id" varchar(255), "timestamp" datetime NOT NULL, "public" bool NOT NULL, "action_object_content_type_id" integer, "actor_content_type_id" integer NOT NULL, "recipient_id" integer NOT NULL, "target_content_type_id" integer, "deleted" bool NOT NULL, "emailed" bool NOT NULL, "data" text, "unread" bool NOT NULL, FOREIGN KEY("recipient_id") REFERENCES "reg_group_user"("id") DEFERRABLE INITIALLY DEFERRED, FOREIGN KEY("target_content_type_id") REFERENCES "django_content_type"("id") … -
ImproperlyConfigured exception when starting server. "The included URLconf 'percentsystem .urls' does not appear to have any patterns in it"
I making a Django website, and everything was alright until the moment when i added new path in urls.py: app's urls.py from django.urls import path from . import views urlpatterns = [ path('', views.members_list, name='members_list_url'), path('create/', views.MemberCreate.as_view(), name='member_create_url'), path('<str:nickname>/', views.MemberPage.as_view(), name='member_page_url') ] and an error message occured: (venv) D:\Documents\Desktop\percents_system\app\percentsystem>manage.py runserve r Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "D:\Documents\Desktop\percents_system\venv\lib\site-packages\django\urls\ resolvers.py", line 581, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\program files\python36\Lib\threading.py", line 916, in _bootstrap_inn er self.run() File "c:\program files\python36\Lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "D:\Documents\Desktop\percents_system\venv\lib\site-packages\django\utils \autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "D:\Documents\Desktop\percents_system\venv\lib\site-packages\django\core\ management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "D:\Documents\Desktop\percents_system\venv\lib\site-packages\django\core\ management\base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "D:\Documents\Desktop\percents_system\venv\lib\site-packages\django\core\ management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "D:\Documents\Desktop\percents_system\venv\lib\site-packages\django\core\ checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "D:\Documents\Desktop\percents_system\venv\lib\site-packages\django\core\ checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "D:\Documents\Desktop\percents_system\venv\lib\site-packages\django\core\ checks\urls.py", line 23, in check_resolver return check_method() File "D:\Documents\Desktop\percents_system\venv\lib\site-packages\django\urls\ resolvers.py", line 398, in check for pattern in self.url_patterns: File "D:\Documents\Desktop\percents_system\venv\lib\site-packages\django\utils \functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) … -
Django on Nginx subdirectory redirects to root
I have Django 2.2 and am trying to serve it to http://myserver.com/application using Nginx proxy pass. If I try and go to myserver.com/application/admin I get redirect to myserver.com/admin immediately. Is this a setting I should be specifying in Nginx or in Django to avoid this? Django is running in gunicorn, see Nginx.conf: location /static { alias /home/simernes/workspace/django_server/env/static; } location /application { proxy_pass http://localhost:8000/; proxy_redirect off; 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-Proto http; proxy_buffer_size 128k; proxy_buffers 8 128k; proxy_busy_buffers_size 256k; } Finally, this is what my urls.py looks like in a project folder "backend": from django.contrib import admin from django.urls import path from django.conf.urls import url, include FORCE_SCRIPT_NAME="/application" STATIC_ROOT="/home/simernes/workspace/django_server/env/static/" app_name='backend' urlpatterns = [ path('admin/', admin.site.urls), url(r'^', include('api.urls', namespace='api')), ] Furthermore, when I go to the root of myserver.com/application I get an error of 404 not found and: Using the URLconf defined in backend.urls, Django tried these URL patterns, in this order: admin/ ^ auth$ [name='auth'] The current path, /, didn't match any of these. Which is not what I expected, as I am configuring to show the urls available in my api app (see urls.py below), but it's not my main concern with this question so … -
How to pass contenteditable text to value attribute in django html file
I have tried finding resource but couldn't get any. I have a html file in templates folder in my django app as {% for comment in comments %} <li contenteditable = "TRUE" >{{comment.text}} <form contenteditable = "FALSE" action = "{% url 'clickedaccept' %}" method = "POST"> {% csrf_token %} <input type = "hidden" name = "acceptedvalue" value = "{{comment.id}}"> <input type = "hidden" name = "selected_option" value = "{{selected_option}}"> <input type = "hidden" name = "selected_autocomplete" value = "{{selected_autocomplete}}"> <input type = "submit" value = "Accept" id = "{{comment.id}}" > </form> {% endfor %} </li> Here the comment.text is extracted from model and is editable. User can edit the text value. There is a form with post method. I want to send the value of content editable text in value attribute of hidden input. How can I achieve it? -
How to structure a daily habit tracking app
Background I'm a personal trainer and trying to build an app that tracks whether or not my clients are working on their daily habits (and bugs them about it at a chosen time every day). I'd love to hear if any of you all have ideas on how to structure this as I'm new to both Django and coding in general. Models I currently have two models: Habits and Checks. Habits represent "What are you working on improving?" and have a ForeignKey to a user. Checks represent "Did you complete your habit today?" and have a ForeignKey to a habit. Current status There is a nice solution where you create all the Checks for a Habit based on it's end date, but I'm trying to structure this with an indefinite end date because, as a coach, then I can show hard data when someone isn't making progress. Though I am still willing to accept that maybe this app would work better if habits had deadlines. I wrote a custom manage.py script that Heroku runs automatically at the same time every day, but that doesn't scale with users' individual time zones. I run it manually on my local computer. I originally …