Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
dictionary in template tag django
I would like to extract something like bellow: {% for item in query_ %} <td>{{ mydictionary[item.id] }}</td> {% endfor %} which of course gives me a syntax error. For this purpose I have defined a template tag @register.filter('get_value_from_dict') def get_value_from_dict(dict_data, key): if key: return dict_data.get(key) and then use it as follows: {% for item in query_ %} <td>{{ mydictionary | get_value_from_dict : item.id }}</td> {% endfor %} however it doesnt work and gives me the following error: get_value_from_dict requires 2 arguments, 1 provided I was wondering what I am doing wrong. -
What do these lines of code do to my django models?
Hi there I recently started learning the django rest framework by reading the django rest docs. I made it to the Authentication & Permissions chapter and came across these two lines of code; owner = models.ForeignKey('auth.User', related_name='snippets', on_delete=models.CASCADE) highlighted = models.TextField() It says that I should add them to my models, but I dont want to do that without understanding what do they do/mean. Can anyone tell me? -
Django: Is there a way to filter out 503 'service unavilable' responses from mail_admins log handler?
I have django LOGGING configured with standard "mail admins on 500 errors": 'mail_admins': { 'level': 'ERROR', 'filters': ['require_debug_false'], 'class': 'django.utils.log.AdminEmailHandler' }, When I put site into maintenance mode (django-maintenance-mode), it correctly responds with 503 "Service Unavailable" for anonymous requests. This causes a barrage of emails to admins when the site is in maintenance mode. I want to "filter out 503 response IF site is in maintenance mode" to stem the flood. But can't see a simple way to do this (e.g., logging filter would need request to check if site in maintenance mode) I know I could change the maintenance error code to a 400-level error, but that seems like non-semantic hack. Could also suspend admin emails during maintenance, but that requires remember to hack / revert settings file. Hoping someone has a clever idea how to achieve this simply, no hacks. -
How do I set upload/download progress in response? (swift & Django)
How do I get the upload and download progress? Heres how what Im doing in Xcode according to alamofire docs this is supposed to get the progress, buts only printing 0 in download and 1 in upload. AF.download("http://127.0.0.1:8000/") .downloadProgress { progress in print("Download Progress: \(progress.fractionCompleted)") } .responseData { response in if let data = response.value { let image = UIImage(data: data) } } let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov") AF.upload(fileURL, to: "http://127.0.0.1:8000/") .uploadProgress { progress in print("Upload Progress: \(progress.fractionCompleted)") } .downloadProgress { progress in print("Download Progress: \(progress.fractionCompleted)") } .responseDecodable(of: HTTPBinResponse.self) { response in debugPrint(response) } Heres how I'm responding to these requests in Django // for download def test (request): file = File.objects.get(user=curUser) return FileResponse(file.file) //for upload s = File(file=f, user=curUser) s.save() return JsonResponse({'status': 'ok'}) I read that this might be because I need to set up my server so it also sends progress % back. But im not sure how I would implement this. Can someone point me to the right direction? -
React and Django REST not fully authenticating
I built a app with react, django and used DRF, I have a log in page which when successful passed a token, basically, it logs in fine but just noticed that i have a component which gets data from a particular logged in user and i used "IsAuthenticated" as a decorator, I notice it shows in the API, but not in my frontend, I removed "IsAuthenticated" decorator, and check the network then i noticed it shows: 'AnonymousUser' object has no attribute 'follow_user' ... even when im logged in react. Please help I dont understand what is going on. -
Django - Parse a list typed in by user in a form and link each element of the list with the first value of the first field of the form
I am new to django but really want to learn how to use this framework. What want to do : I have a form, that allows the user to create a new client for example. So in this form I have 3 fields : Name Description Skills The 'Skills' field is currently a text area, where the user would copy and paste a list already existing in another document(excel). Therefore, each element is separated by a splitline. What I would like to do is : create in the database the client entered by the user In the database, link the description entered by the user to the client In the database, link each skill entered by the user to the name so that I can work on them independantly of each other in further functions/apps. I don't want all of the skills to be linked to the client as one big bloc. So I read the documentation and thought about using a ForeignKey. The thing is I was unable to get an input text area when using a ForeignKey. Everytime I used it I got an empty 'select list'... An even though I would be able to get that, I … -
Django serve file in memory instead of saving on disk
I want to render plot (matplotlib) in one place of code and then in ViewSet serve to it user without saving on disk. I tried to use io library to keep file in memory, but it seems that always something is wrong. My code where I save plot on disk: def some_func(self): ...generating plot... filename = self.generate_path() # generate random name for file plt.savefig(filename, transparent=True) return filename Code of ViewSet: class SomeViewsSet(ViewSet): def create(self, request): ... some code ... path = some_func() name = path.split('/')[-1] with open(path, 'rb') as file: response = HttpResponse(file, content_type=guess_type(path)[0]) response['Content-Length'] = len(response.content) response['Content-Disposition'] = f'attachment; filename={name}' return response -
Rendering the page in django with html form
I have these two functions, one of them (first one) adds a new entry and the second one edits the entry: def add_entry(request): if request.method == 'POST': form = AddForm(request.POST) if form.is_valid(): title = form.cleaned_data["title"] content = form.cleaned_data["content"] if util.get_entry(title) is None: util.save_entry(title, content) return redirect('entry', title) else: return render(request, "encyclopedia/add_entry.html", { "form": AddForm(), "title": title }) return render(request, "encyclopedia/add_entry.html", { "form": AddForm() }) def edit_entry(request, title): content = util.get_entry(title) if request.method == 'POST': form = AddForm(request.POST) if form.is_valid(): title = form.cleaned_data["title"] content = form.cleaned_data["content"] util.save_entry(title, content) return redirect('entry', title) return render(request, "encyclopedia/edit_entry.html", { "title": title, "content": content Here is my edit_entry.html page: {% extends "encyclopedia/layout.html" %} {% block title %} Edit page {% endblock %} {% block body %} <form action="{% url 'edit_entry' title %}" method="POST"> {% csrf_token %} <h5>Title</h5> <input type="text" value="{{ title }}"> <h5>Content</h5> <textarea cols="30" rows="10">{{ content }}</textarea> <input type="submit" value="Save Editing"> </form> {% endblock %} This is add_entry.html template {% extends "encyclopedia/layout.html" %} {% block title %} Add new entry {% endblock %} {% block body %} <h1>Create a new page</h1> {% if title %} <h6 style="color: red;">"{{title}}" page is already exists. Please, enter a different title</h6> {% endif %} <form action="{% url 'add_entry' %}" … -
How to use dispatch_uid to avoid duplication Signals correctly
Helloo, I am trying to apply using a dispatch_uid="my_unique_identifier" in order to avoid duplicate signals sent in my project. I have searched for several similar answers and read the following documentation but I am not sure what I am missing: https://docs.djangoproject.com/en/3.1/topics/signals/#preventing-duplicate-signals In my project there are posts that are written by Author, each post has a like button which when clicked by a user notification is created and sent to the author. Until here everything is fine except that 2 notifications are sent instead of 1. I have tried the following but it did not have any effect and I am still receiving 2 notifications So here it is: Here is the Like model.py class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=8) def user_liked_post(sender, instance, *args, **kwargs): like = instance if like.value=='Like': post = like.post sender = like.user dispatch_uid = "my_unique_identifier" notify = Notification(post=post, sender=sender, user=post.author, notification_type=1) notify.save() post_save.connect(Like.user_liked_post, sender=Like, dispatch_uid="my_unique_identifier") Here is the notifications model class Notification(models.Model): NOTIFICATION_TYPES=((1,'Like'),(2,'Comment'),(3,'Admin')) post = models.ForeignKey('blog.Post', on_delete=models.CASCADE, related_name="noti_post", blank=True, null=True) sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name="noti_from_user") user = models.ForeignKey(User, on_delete=models.CASCADE,related_name="noti_to_user") notification_type= models.IntegerField(choices=NOTIFICATION_TYPES) def __str__(self): return str(self.post) My question is how to use dispatch_uid="my_unique_identifier" correctly inorder to avoid duplicated … -
No effect from the signals
I want my app users to listen to the action of creating a User instance and exactly after that initialise (create) an Account instance: Unfortunately the following does not work at all: from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Account @receiver(post_save, sender=User) def create_account(sender, instance, created, **kwargs): if created: Account.objects.create(user=instance) @receiver(post_save, sender=User) def save_account(sender, instance, **kwargs): instance.account.save() and my apps.py from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals I create a user but it does not dispatch the action for the receivers to created an Account instance. At leas I cannot see them in the Django default administration region. -
How to get a column value from a HTML table using django
I have a HTML table with checkboxes. I want to read the first column value based on the row selected using the checkbox. To read the values, a function is called after selecting the checkbox and clicking a button. Table look this way <a href="{% url 'app-analyze_retina' %}"> <button onclick="" class="patient-add-btn button1"> Send for Analysis </button> </a> {% if btn_clicked %} <div> <table class="table" id="patient_list"> <thead class="thead-dark"> <tr> <th scope="col">Patient ID</th> <th scope="col">First Name</th> <th scope="col">Last Name</th> <th scope="col">Result/Severity Level</th> <th scope="col">Tested on</th> <th scope="col">AI confidence</th> <th scope="col">Comments</th> </tr> </thead> <tbody> {% for patient in data %} <tr> <td bgcolor="mediumaquagreen"> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" name="checks" id={{patient.0}} value="{{patient.1}}"> <label class="custom-control-label" for={{patient.0}}>{{patient.1}}</label> </div> <!-- <td bgcolor="mediumaquagreen" > {{ patient.1 }}</td>--> <td bgcolor="mediumaquagreen">{{patient.2}}</td> <td bgcolor="mediumaquagreen" >{{patient.3}}</td> <td bgcolor="mediumaquagreen">2.846</td> <td bgcolor="mediumaquagreen">-</td> <td bgcolor="mediumaquagreen" >Cristina</td> <td bgcolor="mediumaquagreen" >913</td> </td> </tr> {% endfor %} </tbody> </table> </div> {% endif %} Function to read the values def analyze_img(request): c = request.POST.getlist('checks') print(c) First I was trying to check whether I am able to read a checkbox but it returns an empty list. -
FieldError django
Please I need help, I dont know where the problem is coming from, please see the code below @api_view(['GET']) @permission_classes([IsAuthenticated]) def post_feed_view(request, *args, **kwargs): user = request.user profiles = user.follow_user.all() followed_users_id = [] if profiles.exists(): followed_users_id = [x.user.id for x in profiles] followed_users_id.append(user.id) queryset = Post.objects.filter(user__id__in=followed_users_id).order_by("-date_posted") serializer = PostSerializer(queryset, many=True) return Response(serializer.data, status=200) I keep getting this error: Cannot resolve keyword 'user' into field. Choices are: author, author_id, although, in my models, I dont have "User" what I have is "Author". But I dont know where exactly to put in author. I think my problem is that i dont fully understand "request.user". Please help!. =========== This is the Profile and Follow models: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.CharField(max_length=245, null=True) image = models.ImageField(default='default.png', upload_to='profile_pics') interests = models.ManyToManyField(Category, related_name='interests_user') stripe_customer_id = models.CharField(max_length=50, blank=True, null=True) one_click_purchasing = models.BooleanField(default=False) is_vendor = models.BooleanField(default=False) # vendor bvn = models.CharField(max_length=10, null=True, blank=True) description = models.TextField(null=True, blank=True) address = models.CharField(max_length=200, null=True, blank=True) company = models.CharField(max_length=100, null=True, blank=True) # follow_user = models.ManyToManyField('users.Follow') def __str__(self): return f'{self.user.username} Profile' @property def followers(self): return Follow.objects.filter(follow_user=self.user).count() @property def following(self): return Follow.objects.filter(user=self.user).count() def save(self, force_insert=False, force_update=False, using=None, update_fields=None): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size … -
How to modify Bootstrap 4 form validation information presentation in Django?
I am using Django and Bootstrap 4. I want to customize the way form validation information is displayed in a template I am using. When an error occurs in the current template, the invalid input element has a red outline and the error message is displayed as a pop-up. Also, the input elements that have been inputted correctly don't have a green outline, they just remain without an outline. I'd like to do the following: display the error message underneath the field when an error occurs give the green outline to the fields whose input is correct I tried multiple solutions, including: this tutorial this GitHub gist the Stack Overflow answers from this question None worked from my case. My current code: submit_job_listing.html (the template): {% extends "base.html" %} {% block title %} Submit a job {% endblock %} {% block nav_item_post_a_job %}active{% endblock nav_item_post_a_job %} {% block head %} {{ job_listing_form.media.css }} {% endblock %} {% block content %} <h1>Submit a job listing</h1> <div class="container"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="row text-center"> <h2> <b>Job listing information</b> </h2> </div> <br/> {% for field in job_listing_form.visible_fields %} <div class="form-group"> <div class="row"> <p>{{ field.label_tag }}</p> </div> <div class="row"> {% if … -
Django graphen Create Mution fireing Error
These are my schmema import graphene from graphene import relay, ObjectType, Mutation from graphene_django import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField from cookbook.models import Ingredient class IngredientType(DjangoObjectType): class Meta: model = Ingredient class IngredientCreate(Mutation): class Arguments: name = graphene.String(required=True) note = graphene.String(required=True) id = graphene.ID() ingredient = graphene.Field(IngredientType) @classmethod def mutate(cls, root, info, name, note, id): ingredient = IngredientType.objects.create( name = name, note = note ) return IngredientCreate(ingredient=ingredient) class Query(graphene.ObjectType): create_ingredient = IngredientCreate.Field() and this is my models. class Ingredient(models.Model): name = models.CharField(max_length=100) notes = models.TextField() I am trying to create Ingredient from graphql django gui but fires me syntax error { createIngredient( name: 'rice cooking', note: 'a simple note', ) } Can anyone tell me please what is the possible reasone that i cant create a record? -
Django/Pillow ImageField - image not showing
I am trying to follow along to a Codemy Youtube tutorial and I am not having the same results. I want to display an image on a Django website. I have installed Pillow correctly and followed the tutorial step by step but I am only getting a broken image icon on the webpage. Copied image url from broken img icon - http://127.0.0.1:8000/media/images/MX1A1063.JPG [1]: https://i.stack.imgur.com/51HgB.png - settings.py [2]: https://i.stack.imgur.com/bMy0F.png - Broken img icon [3]: https://i.stack.imgur.com/gg55Z.png - forms.py [4]: https://i.stack.imgur.com/AYeGm.png - terminal window [5]: https://i.stack.imgur.com/3UhvU.png - pip freeze [6]: https://i.stack.imgur.com/5QzGR.png - models.py [7]: https://i.stack.imgur.com/PKHxF.png - product_detail.html [8]: https://i.stack.imgur.com/EyzDy.png - images folder in main src folder Tutorial - https://www.youtube.com/watch?v=ygzGr51dbsY&ab_channel=Codemy.com -
how can i get all attribute data from ManyToMany field Django?
i want to get all attribute data of articles in SetRundown forms like title, category, author via ManyToManyfield i want to show all article in Rundown form with title category and author name can anybody know how can i do this...? if i run my code with {% render_field form.articles %} then it will show the all articles title but i want the category and author name too with titles.... models.py class Article(models.Model): title = models.CharField(max_length=300, help_text="Short title") category = models.ForeignKey(Category, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) class SetRundown(models.Model): pool_title = models.CharField(max_length=200) articles = models.ManyToManyField(Article) forms.py from django import forms class SetRundownForm(forms.ModelForm): class Meta: model = SetRundown fields = ['pool_title', 'time_pool', 'articles'] def __init__(self, *args, **kwargs): super(SetRundownForm, self).__init__(*args, **kwargs) self.fields['articles'].queryset = Article.objects.filter(story_status='fr') create_form.html <form method="POST">{% csrf_token %} {% render_field form.pool_title type="text" %} {% render_field form.time_pool type="menu" %} {% for article in form.articles %} {{ article.title }} {{ article.category }} {{ article.author.username }} {% endfor %} <button class="btn btn-secondary" type="submit">Submit</button> </form> {% endblock %} -
How can I create model instances in a .py file?
So when I create a model instance using the CLI, it works. The model: class Post(models.Model): title = models.CharField(max_length=100) cover = models.ImageField(upload_to='images/') description = models.TextField(blank=True) def __str__(self): return self.title Then I did: $ python manage.py shell >>>from blog.models import Post >>>filename = 'images/s.png' >>>Post.objects.create(title=filename.split('/')[-1], cover=filename, description='testing') And it worked, it showed up on the page that I'm displaying these models at. However, when I take this same code and put it in a file, portfolio_sync.py, it doesn't work. from blog.models import Post filename = 'images/s.png' Post.objects.create(title=filename.split('/')[-1], cover=filename, description='testing') I get this error: Traceback (most recent call last): File "portolio_sync.py", line 1, in <module> from models import Post File "/Users/rfrigo/dev/ryanfrigo/blog/models.py", line 4, in <module> class Post(models.Model): File "/Users/rfrigo/anaconda3/lib/python3.7/site-packages/django/db/models/base.py", line 87, in __new__ app_config = apps.get_containing_app_config(module) File "/Users/rfrigo/anaconda3/lib/python3.7/site-packages/django/apps/registry.py", line 249, in get_containing_app_config self.check_apps_ready() File "/Users/rfrigo/anaconda3/lib/python3.7/site-packages/django/apps/registry.py", line 131, in check_apps_ready settings.INSTALLED_APPS File "/Users/rfrigo/anaconda3/lib/python3.7/site-packages/django/conf/__init__.py", line 57, in __getattr__ self._setup(name) File "/Users/rfrigo/anaconda3/lib/python3.7/site-packages/django/conf/__init__.py", line 42, in _setup % (desc, ENVIRONMENT_VARIABLE)) django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. How can I fix this, and create a model instance in a .py file? (Because I need to loop through a bunch of … -
Calculate File upload time on server
I want to calculate how much time a particular encryption algorithm takes while uploading files on the server. I have used time.process_time() , time.time() like function to calculate the time taken by Encryption algorithm,but they are giving inaccurate values on server. start_time = time.process_time() encryption_algo() toatl_time = time.process_time() - start_time The output on the local machine is accurate but on the server, it's not. Ex:- if 6.00s on local then it is like 0.444s on a server, So how can I effectively calculate the time taken to encrypt file? -
I want to make virtual payment method but its not working
i am trying to make a system where customer can buy with thier coin.I have already assigned some coin to make purchase but its not workin.Actually i am trying to substract with the product price and account balance but its not working.For this i made a post method: view.py: def post(self, request, *args, **kwargs): ids = list(request.session.get('cart').keys()) cart_products = Product.get_products_id(ids) product_prices = list(map(self.map_func, cart_products)) total_due = sum(product_prices) balance = request.session['customer']['coin'] if balance >= total_due: balance = balance - total_due print(balance) # Customer.objects.filter(id = request.session['customer']['id']).update(coin=balance) customer = Customer.objects.get(id = request.session['customer']['id']) customer.coin = balance customer.save() # request.session['customer']['coin'] = balance return HttpResponse(balance) return HttpResponse("Failed") Here is my index {% extends 'Home/header.html' %} {% load cart %} {% block content %} {{user_orders.product.name}} {{user_orders.product.price}} {{total_due}} <form action="" method="POST"> {% csrf_token %} <input type="submit" name="payment_coin"> </form> {{request.session.customer}} {% endblock %} I dont know why its not working well. I got stuck here please help -
How to clean a list in a template
I am currently working on my first website. Which is a rna to a protein translator. What it does is you input a dna chain and it translates it into a protein. However, when i get the protein, it appears like this: As you can see, the protein isn't cleaned, which means that instead of appearing as Isoleucine, glycine; it appears as ['Isoleucine','Glycine'] Here's the code for that: (my guess is there's a problem in the output part) class TranslatorView(View): template_name = 'main/translated.html' rna_mapper = { "a": "u", "t": "a", "c": "g", "g": "c" } amino_mapper={ "aat": "Asparagine", "aac": "Asparagine", "aaa": "Lysine", "aag": "Lysine", "act": "Threonine", "acc": "Threonine", "aca": "Threonine", "acg": "Threonine", "agt": "Serine", "agc": "Serine", "aga": "Arginine", "agg": "Arginine", "att": "Isoleucine", "atc": "Isoleucine", "ata": "Isoleucine", "atg": "Methionine", "cat": "Histidine", "cac": "Histidine", "caa": "Glutamine", "cag": "Glutamine", "cct": "Proline", "ccc": "Proline", "cca": "Proline", "ccg": "Proline", "cgt": "Arginine", "cgc": "Arginine", "cga": "Arginine", "cgg": "Arginine", "ctt": "Leucine", "ctc": "Leucine", "cta": "Leucine", "ctg": "Leucine", "gat": "Aspartic", "gac": "Aspartic", "gaa": "Glutamic", "gag": "Glutamic", "gct": "Alanine", "gcc": "Alanine", "gca": "Alanine", "gcg": "Alanine", "ggt": "Glycine", "ggc": "Glycine", "gga": "Glycine", "ggg": "Glycine", "gtt": "Valine", "gtc": "Valine", "gta": "Valine", "gtg": "Valine", "tat": "Tyrosine", "tac": "Tyrosine", "taa": "Stop", "tag": "Stop", … -
Django delete item from popup window
I want to delete specific order from my popup window in django. So my urlpatterns is something like [I guess I have something wrong here] in url.py: urlpatterns = [ path('panel', views.home, name='panel'), path('panel/profile/<str:customer_username>', views.profile, name='profile'), path('<str:order_id>', views.deleteOrder, name='delete_order'), ] and in view.py I have a function for deleting specific order: def deleteOrder(request, order_id): order_item = Order.objects.get(id=order_id) print(order_item) if request.method == 'POST': order_item.delete() return redirect('') context = {'order_item': order_item} return render(request, '', context) And finally in URL [each user profile page] localhost:8000/panel/profile/testuser I have: <!-- Button trigger modal --> <a href="" data-toggle="modal" data-target="#exampleModalCenter"> <i class="la la-edit edit"></i> </a> <!-- Modal --> <div class="modal fade" id="exampleModalCenter" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLongTitle">Delete Order</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <h5>{{order.oid}}</h5> </div> <div class="modal-footer"> <div class="col-6 text-left"> <div class="previous"> <form action="{% url 'delete_order' order_item.id %}" method="POST"> {% csrf_token %} <input class="btn btn-danger btn-sm btn-block" type="submit" name="Yes" value="Yes"> </form> </div> </div> <div class="col-6 text-left"> <div class="next"> <a class="btn btn-warning btn-sm btn-block" href="">No</a> </div> </div> </div> </div> </div> </div> The error is abount addressing I guess: DoesNotExist at /panel/profile/{% url 'delete_order' order_item.id -
OneToOneField in Django is not working properly
In my 'users' app in my Django project I have the following code for my model: from django.db import models from django.contrib.auth.models import User class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField (default='default.jpg', upload_to='profile_pics') bio = models.TextField(blank=True) def __str__(self): return f'{self.user.username} Profile' I have done the migrations correctly and registered this to admin.site.register My problem is that the field 'user' does not make an Account instance. In other words I cannot access to the data in the fields of Account model through User instances. For example I cannot access to user.account.bio or user.account.image -
Django/Js: how to post a form without reloading whole page
My application currently flows through 3 pages: User selects question in index page User submits answer in answer page User is presented with result in results page. I want to compress that down to a single page where the user submits an answer to the question and result is shown on the same page. The following django-template code separates questions with Bootstrap accordion. How do I post the form without refreshing the whole page? I want to be able to display the result on the page, update CSS styling with Javascript etc. <h2>{{ category.title }}</h2> <div class="accordion" id="accordion{{category.title}}"> {% for challenge in category.challenge_set.all %} <div class="card"> <div class="card-header" id="heading{{challenge.id}}"> <h2 class="mb-0"> <button class="btn btn-link btn-block text-left" type="button" data-toggle="collapse" data-target="#collapse{{challenge.id}}" aria-expanded="true" aria-controls="collapse{{challenge.id}}"> {{ challenge.question_text }} - {{ challenge.point_value }} points </button> </h2> </div> <div id="collapse{{challenge.id}}" class="collapse in" aria-labelledby="heading{{challenge.id}}" data-parent="#accordion{{category.title}}"> <div class="card-body"> <p>{{ challenge.description }}</p> <form action="{% url 'challenges:answer' challenge.id %}" method="post"> {% if challenge|is_answered:request %} <label for="answered">Answer</label> <input type="text" name="answered" id="answered" value="{{ challenge.answer_text }}" readonly> {% else %} {% csrf_token %} <label for="answer">Answer</label> <input type="text" name="answer" id="answer"> <input type="submit" value="Submit"> {% endif %} </form> </div> </div> {% endfor %} </div> Here is the view: def index(request): context = {'challenges_by_category_list': Category.objects.all()} return … -
Sending data from ESP8266 to server [closed]
I need to somehow send data from my ESP8266 to my pc. I want to receive data from esp on pc and log them to csv file for example. I would like to visualise them and make some kind of gui but it's not necessary. Minimum goal is to be able to receive data from many esp devices and log them. I don't really know what should i use to do so. At the moment i am able to send messages through MQTT but i have no clue how to make some kind of server on my pc. I thought about doing website with django but i'm not sure if it is a good idea tbh. I know about generally available sites as thingspeak.com but i want to avoid using it. Any tips what technologies, languages, frameworks would be best to use in this case? I would be grateful for any advices. -
How to allow to edit field in django admin list depending on a value?
I need to allow to change a value of a field if it doesn't equal to 0. I found that I need to override get_changelist_form but don't know how. I tried to override form but it raised Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form OrderChangeListForm needs updating. What I need: def get_changelist_form(self, request, **kwargs): # if instance.status == 0 make it not editable return super(MyModelAdmin, self).get_changelist_form(request, **kwargs) My Model: class ModelAdmin (admin.ModelAdmin): list_display = ['id', 'client', 'status'] list_editable = ('status',)