Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I display content cards evenly spaced including margin sides using flexbox
HTML <section class="cards"> {% for m in mcontent %} <div class="card"> <div class="top"> <div class="year">{{m.Year}}</div> <div class="wish_icon"><a href="#" class="add_to_wishlist">wishicon</a></div> </div> <div class="middle"> <div class="img-container"><img src="{{ m.Image.url }}"></div> </div> <div class="bottom"> <div class="charge">{{m.charge}}</div> <div class="list">{{m.list}}</div> </div> </div> {% endfor %} </section> CSS .cards { display: flex; justify-content: space-around; flex-wrap: wrap; flex-direction: row; } .card { width: 250px; height: 350; border-radius: 10px; box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2); background-color: white; margin-left: 30px; margin-right: 30px; margin-top: 30px; margin-bottom: 30px; } what it looks like: [1]: https://i.stack.imgur.com/KWiLm.png what it should look like: [2]: https://i.stack.imgur.com/t2WuA.png So Ik that I can solve this with justify-content: flex-start; but that leaves me with unwanted space on the right side and I'm kinda lost, any help is appreciated, Thnx! -
can not get input/outputs from DJANGO
I am new to Django.While practicing. I downloaded HTML template and managed to modify it to load up with django. my issue that i can not get any inputs or outputs from Django<>HTML.I do not know where is the problem. view.py from django.shortcuts import render def home(request): return render(request, 'home.html' ,{}) def contact(request): if request.method == "POST" : username_1 = request.POST["username"] return render(request, 'home.html', {'username_1' : username_1}) login_page/urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home"), ] home.html {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>Login V1</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!--===============================================================================================--> <link rel="icon" type="image/png" href="{%static 'login_page/images/icons/favicon.ico' %}"/> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{%static 'login_page/vendor/bootstrap/css/bootstrap.min.css' %}"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{%static 'login_page/fonts/font-awesome-4.7.0/css/font-awesome.min.css' %}"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{%static 'login_page/vendor/animate/animate.css' %}"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{%static 'login_page/vendor/css-hamburgers/hamburgers.min.css' %}"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{%static 'login_page/vendor/select2/select2.min.css' %}"> <!--===============================================================================================--> <link rel="stylesheet" type="text/css" href="{%static 'login_page/css/util.css' %}"> <link rel="stylesheet" type="text/css" href="{%static 'login_page/css/main.css' %}"> <!--===============================================================================================--> </head> <body> <div class="limiter"> <div class="container-login100"> <div class="wrap-login100"> <div class="login100-pic js-tilt" data-tilt> <img src={%static 'login_page/images/img-01.png'%} alt="IMG"> </div> <form class="login100-form validate-form" action="{% url 'home' %}" method="post" > {% csrf_token %} <span class="login100-form-title"> {{ username_1 }} </span> <div class="wrap-input100 validate-input" data-validate = "Valid email is … -
How to convert textarea as list and save to into postgreSQL in django?
So here's the situation, I have a textarea where user gives his timetable, when submitted, I want to break the timetable into some lists such as Monday,Tuesday..... and save it to database The timetable is as follows: Theory Start 08:00 09:00 10:00 11:00 12:00 - Lunch 14:00 15:00 16:00 17:00 18:00 18:50 19:01 End 08:50 09:50 10:50 11:50 12:50 - Lunch 14:50 15:50 16:50 17:50 18:50 19:00 19:50 Lab Start 08:00 08:46 10:00 10:46 11:31 12:16 Lunch 14:00 14:46 16:00 16:46 17:31 18:16 - End 08:45 09:30 10:45 11:30 12:15 13:00 Lunch 14:45 15:30 16:45 17:30 18:15 19:00 - MON Theory A1-MAT3003-TH-CDMM105 F1-MEE1018-TH-GDNG08A D1-MEE1009-ETH-MB111 TB1-MEE3004-TH-MB214 TG1-MEE2022-TH-MB213 - Lunch A2 F2 D2-STS3205-SS-MB225 TB2 TG2 - V3 Lab L1 L2 L3 L4 L5 L6 Lunch L31 L32 L33 L34 L35 L36 - TUE Theory B1-MEE3004-TH-MB214 G1-MEE2022-TH-MB213 E1-MEE3001-TH-MB309 TC1 TAA1-MAT3003-TH-CDMM105 - Lunch B2 G2 E2 TC2 TAA2 - V4 Lab L7 L8 L9 L10 L11 L12 Lunch L37-CHE1006-ELA-SMVG26A L38-CHE1006-ELA-SMVG26A L39 L40 L41 L42 - WED Theory C1-CHE1006-ETH-SMV109 A1-MAT3003-TH-CDMM105 F1-MEE1018-TH-GDNG08A V1-MAT3003-TH-CDMM105 V2-MEE3001-TH-MB309 - Lunch C2 A2 F2 TD2-STS3205-SS-MB225 TBB2 - V5 Lab L13 L14 L15 L16 L17 L18 Lunch L43 L44 L45 L46 L47 L48 - THU Theory D1-MEE1009-ETH-MB111 B1-MEE3004-TH-MB214 G1-MEE2022-TH-MB213 TE1-MEE3001-TH-MB309 TCC1 - … -
Sharing Post By Email In Django 3
I want to pass link of certain post as my message in sendmail attribute. I can do it using function based views easily but unable to do with Class Based views.I don't know how to extract link to a object in class based views. Can You help with it? -
Why i am seeing bootstrap cards like this?
I am using Django to create a basic web page. I am new to python as well as django. I am seeing bootstrap cards in one row on the screen.But I want cards shown responsively according to screen size. Any suggestions? {% extends 'base.html'%} {% block content %} <h1>Products</h1> <div class="row"> {% for product in products %} <div class="col"> <div class="card" style="width: 18rem;"> <img src="{{ product.image_url }}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="card-title">{{ product.name }}</h5> <p class="card-text">Rs. {{ product.price }}</p> <a href="#" class="btn btn-primary">Add to Cart</a> </div> </div> </div> {% endfor %} </div> {% endblock %}[enter image description here][1] -
How to use inlcude and content block in HTML code
I have a question for you. I have the following structure: __Base.html __main_sidebar.html __conto_economico.html The _main_sidebar.html is the following: {% block nav_links_ul %} <nav class="mt-2"> <ul class="nav nav-pills nav-sidebar flex-column" data-widget="treeview" role="menu" data-accordion="false"> {% block nav_links_outer %} <li class="nav-header">{% block nav_heading %}PERFORMANCE MONITORING{% endblock %}</li> {% block nav_links %} <li class="nav-item"> <a href="#" class="nav-link"> <i class="nav-icon fas fa-tachometer-alt"></i> <p>Dashboard</p> </a> </li> <li class="nav-item"> <a href="/conto_economico" class="nav-link"> <i class="nav-icon fas fa-chart-bar"></i> <p>Conto Economico</p> </a> </li> It is include in my base.html: {% block nav_sidebar %} {% include 'adminlte/lib/_main_sidebar.html' %} {% endblock %} My conto_economico.html is an extends of base.html {% extends 'adminlte/base.html' %} {% block content %} {% endblock content %} Now I want that, when I press on the link in my sidebar (ad example /conto_economico) and the new page is upload, I want tha the relative nav-link become nav-link active as the following: <a href="/conto_economico" class="nav-link active"> Could I get it? -
How does Almofire "upload" images from Swift to a backend?
I am trying to upload images from Swift to my Django backend so that I can store them in Google Cloud Storage and access them as "foreign keys" in my database models in django. There seems to be a built in library to bridge Django models and Google Storage https://django-storages.readthedocs.io/en/latest/backends/gcloud.html. Reference upload image to server using Alamofire. Before sending an image to the backend, the image is converted into a UIImageJPEGRepresentation. How exactly is Alamofire then sending the image via "multipartFormData"? Is it simply sending the raw UIImageJPEGRepresentation as a string? I am asking this because I need to somehow convert this image data I receive in my backend and store it in a Django model and simultaneously upload it to Google Storage. From the documentation: >>> class Resume(models.Model): ... pdf = models.FileField(upload_to='pdfs') ... photos = models.ImageField(upload_to='photos') To store a local file to cloud storage and at the same time in a model field: >>> obj1.pdf.save('django_test.txt', ContentFile('content')) >>> obj1.pdf <FieldFile: tests/django_test.txt> Would something like this work for an image sent from Alamofire? >>> obj1.photos.save(<Insert whatever was sent from Alamofire>) If so, how do you access the data sent from Alamofire? -
Problem in loading JS files on web, but working in local
I'm using django with gunicorn and nginx, all js files are loading properly in locally, but on the website, some JS files not working properly. it is not every day but it happens sometimes in a while. where should I search for the problem? is this from the server or CDN server? -
Javascript console.log command in Django is not working?
i am trying to print in chrome console for debugging. if i am running the same code without Django then console.log() is working fine, but while using it in Django console.log() is not printing anything. i searched the web about it and i didn't got any direct answer. var inputDiv = document.querySelectorAll(".todo"); console.log(inputDiv) The above code is from my Js file in my project. If i am directly executing these code in chrome console then it's working fine.I am also new to Django please help. -
RoleLeaderSerializer' object is not callable?
When I try to get I receive this error object is not callable model class RoleLeader(AbstractUser): cellphone = models.CharField(max_length=10, unique=True) photo = models.ImageField(upload_to='photoleaderprofile') def __str__(self): return self.username serializer class RoleLeaderSerializer(serializers.ModelSerializer): """ Serialziador para ver usuarios y sus roles """ class Meta: model = RoleLeader fields = '__all__' viewset class RoleLeaderViewSet(viewsets.ModelViewSet): queryset = RoleLeader.objects.all() serializer_class = RoleLeaderSerializer -
Which Android system can I use between Java and python
I have web project in Python Django and I want to make Android app for my website Am not good in Android app so if python can, can be good idea to make Android app or is Java good idea, I need to learn and do it myself So which can I learn Your help are appreciated -
Django Error from views when submitting Comment Button
Helloo, I have created a comment button for my blog posts and I am getting "This page isn’t working" after submitting the comment button and I don't know the reason. I can add comments from the admin but can not submit as a user from website I am not sure what needs to be changed in the views.py class PostDetailView(DetailView): model = Post template_name = "post_detail.html" def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, id=self.kwargs['pk']) comments = Comment.objects.filter(post=post).order_by('-id') total_likes = post.total_likes() liked = False if post.likes.filter(id=self.request.user.id).exists(): liked = True if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) if comment_form.is_valid(): content = self.request.POST.get('content') comment = Comment.objects.create( post=post, user=request.user, content=content) comment.save() return HttpResponseRedirect(post.get_absolute_url()) else: comment_form = CommentForm() context["total_likes"] = total_likes context["liked"] = liked context["comments"] = comments context["comment_form"] = comment_form return context -
Uncaught SyntaxError: Invalid or unexpected token in <input id={{ vendor.id }}
I'm trying to submit the form on click function on input[type='checkbox'] without refreshing the page using ajax-jquery. Btw I'm developing a Django web app. Here is my Form element code- <form action="{% url 'change_account_switch' vendor.id %}" method="post"> {% csrf_token %} <div class="custom-control custom-switch"> <input onclick="switchAcc({{ vendor.id }});" type="checkbox" name="switch" class="custom-control-input" id="customSwitch1" checked> <label class="custom-control-label" for="customSwitch1">Enable</label> </div> </form> Here is my JS code- function switchAcc(doc_id) { let switchBtn = $('input[name="switch"]').checked; $.ajax({ {#url: '/ajax/change_account_switch/{{ doc_id }}',#} url: $(this.form).attr('action'), data: { 'status': switchBtn }, dataType: 'json', success: function (data) { console.log(data) if (data.is_done) { alert("A user with this username already exists."); } } error: function (e) { console.log(e.message); } }); } Django views.py ---- @login_required(login_url='/login/') def change_account_switch(request, doc_id): is_done = False ref = db.collection('vendorUsers').document(doc_id) switch = request.GET.get('status', None) ref.set({ 'accountEnabled': switch, }) if not ref.get().to_dict()['accountEnabled'] == switch: is_done = True data = { 'is_done': is_done } return JsonResponse(data)l̥ -
OperationalError pymysql.connections in _read_bytes error(2013, 'Lost connection to MySQL server during query')
Now I'm in big hard trouble because of mysql connection loss. sometimes server starts to make some mysql related errors. Develope envrioments are as following. AWS EC2, AWS DB t2.small, MySQL(CONN MAX AGE 60sec, WAIT_TIMEOUT 300sec) Ubuntu 18, Django 1.11, Python3.6 While apscheduler threads are running, it abruptly happens while writing data on AWS mysql DB. Thank you so much in advance! pymysql/connections.py in _read_bytes at line 707 self._force_close() raise if len(data) < num_bytes: self._force_close() raise err.OperationalError( CR.CR_SERVER_LOST, "Lost connection to MySQL server during query") return data def _write_bytes(self, data): self._sock.settimeout(self._write_timeout) try: Django SQL query is as following: SELECT `django_apscheduler_djangojob`.`id`, `django_apscheduler_djangojob`.`job_state` FROM `django_apscheduler_djangojob` WHERE `django_apscheduler_djangojob`.`next_run_time` <= %s ORDER BY `django_apscheduler_djangojob`.`next_run_time` ASC OperationalError: (2013, 'Lost connection to MySQL server during query') -
This is my first time to use formset of django, but it reports an error "['ManagementForm data is missing or has been tampered with']"
def add_score(request, teacher_uid, course_uid): """The teacher added, deleted, revised and checked the students' grades""" teacher = User.objects.get(uid=teacher_uid) course = Course.objects.get(uid=course_uid) students = course.course_student.o`enter code here`rder_by('-date_joined') # 该课程的所有学生 ScoreFormSet = formset_factory(ScoreForm, extra=len(students)) scores = [] for student in students: scores.append(Score.objects.get(student=student, course=course)) if request.method != 'POST': print(404) formset = ScoreFormSet()#(instance=Score) else: formset = ScoreFormSet(request.POST) if formset.is_valid(): print(403) count = 0 for form in formset: scores[count].score = form.cleaned_data('score') scores[count].save() count = count + 1 ScoreAndForm = zip(scores, formset) context = {'teacher': teacher, 'students': students, 'course': course, 'ScoreAndForm': ScoreAndForm} return render(request, 'apps/add_score.html', context) <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{ course }}</title> </head> <body> {% block content %} <p> <h3>《{{ course }}》课程管理</h3> </p> <form action="{% url 'apps:add_score' teacher.uid course.uid %}" method='post'> {% csrf_token %} {{ formset.management_form }} <table border="2"> <tr> <th>学生</th> <th>成绩</th> <th>更改成绩</th> </tr> {% for score, form in ScoreAndForm %} <p> <tr> <td>{{ score.student }}</td> {% if score.score == -1 %} <td>尚未录入成绩</td> {% else %} <td>scores.score</td> {% endif %} <td>{{ form.as_p }}</td> </tr> </p> {% empty %} {% endfor %} </table> <button name="submit">提交更改</button> </form> {% endblock content %} </body> </html> -
Issues with changin/updating stripe subscription (django)
Currently have this code for one of the subscriptions that I have available on my site. The code checks to see if the user has a plan already, if they don't, the else statement is run (works fine) and if they do, the code for updating their current subscription is replaced with the new subscription.(not working) @login_required def charge(request): user_info = request.user.profile email = user_info.inbox if request.method == 'POST': #returns card token in terminal print('Data:', request.POST) user_plan = request.user.profile.current_plan if user_plan != 'None': '''if they have a plan already, override that plan with this new plan this is using an already created user''' #this throws an error right now new_plan = stripe.Subscription.modify( #the current plan(wanting to change) user_info.subscription_id, cancel_at_period_end=True, proration_behavior='create_prorations', #the new subscription items=[{'plan':'price_HHU1Y81pU1wrNp',}] ) user_info.subscription_id = new_plan.id #if they don't have a subscription already else: amount = 10 customer = stripe.Customer.create( email=email, source=request.POST['stripeToken'], description=user_info.genre_one, ) charge = stripe.Subscription.create( customer=customer.id,#email of logged in person items = [{"plan": "price_HHU1Y81pU1wrNp"}],#change plan id depending on plan chosen ) #updates users current plan with its id and other info user_info.subscription_id = charge.id user_info.customer_id = customer.id user_info.current_plan = 'B' user_info.save() return redirect(reverse('success', args=[amount])) When I try and update the users subscription to the new one … -
createsuperuser fails on postgresql only
I am able to get my code and database to work just fine locally using sqlite3. But when I try and migrate to a postgresql platform, I get errors when I try to create the superuser, but not migrate or makemigration. (trader) bubba@tuna:~/www/src/trader $ ./manage.py makemigrations No changes detected (trader) bubba@tuna:~/www/src/trader $ ./manage.py migrate Operations to perform: Apply all migrations: accounts, admin, auth, contenttypes, sessions Running migrations: No migrations to apply. (trader) bubba@tuna:~/www/src/trader $ ./manage.py createsuperuser Username (leave blank to use 'bubba'): Email address: bubba@trader.com Password: Password (again): Traceback (most recent call last): File "./manage.py", line 21, in <module> main() File "./manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/contrib/auth/models.py", line 158, in create_superuser return self._create_user(username, email, password, **extra_fields) File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/contrib/auth/models.py", line 141, in _create_user user.save(using=self._db) File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/contrib/auth/base_user.py", line 66, in save super().save(*args, **kwargs) File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/db/models/base.py", line 746, in save force_update=force_update, update_fields=update_fields) File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/db/models/base.py", line 795, in save_base update_fields=update_fields, raw=raw, using=using, File "/home/bubba/Env/trader/lib/python3.7/site-packages/django/dispatch/dispatcher.py", … -
How to structure and connect a python project (not a web application) with Django project?
I have a processing engine built in python and a driver program with several components that uses this engine to process some files. See the pictorial representation here. The Engine is used for math calculations. The Driver program has several components. Scanner keeps scanning a folder to check for new files, if found makes entry into DB by calling a API. Scheduler picks new entries made by scanner and schedules them for processing (makes entry into 'jobs' table in DB) Executer picks entries from job table and executes them using the engine and outputs new files. All the components run as separate python process continuously. This is very in efficient, how can I improve this? The use of Django is to provide a DB (so the multiple processes could communicate) and keep a record of how many files are processed. Next came a new requirement to manually check the processed files for errors so a UI was developed for this. Also the assess to the engine was to be made API based. See the new block diagram here Now the entire thing is a huge mess in my opinion. For start, the Django now has to serve 2 different sets … -
How to define request in a CBV
I am adding a comment to posts in a blog I am stumbling upon a minor issue which is trying to define a request to the function Here is the Post-detail class view: class PostDetailView(DetailView): model = Post template_name = "post_detail.html" def get_context_data(self, *args, **kwargs): context = super(PostDetailView, self).get_context_data() post = get_object_or_404(Post, id=self.kwargs['pk']) comments = Comment.objects.filter(post=post).order_by('-id') total_likes = post.total_likes() liked = False if post.likes.filter(id=self.request.user.id).exists(): liked = True if request.method == 'POST': <----- request is not defined. How do I define it? comment_form = CommentForm(request.POST or None) if comment_form.is_valid(): comment.save() else: comment_form = CommentForm() context["total_likes"] = total_likes context["liked"] = liked context["comments"] = comments context["comment_form"] = comment_form return context -
How to open a csv file in another directory from a HTML file
I am new to Django. Below is my project structureMy project structure When I render the table.html file in the templates folder, in the html file I want to access the tomsim_FruitDev.csv file in the output folder. ``` <script> $(document).ready(function(){ $.ajax({ url:"output/tomsim_FruitDev.csv", dataType:"text", success:function(data) { var radiation_data = data.split(/\r?\n|\r/); var table_data = '<table class="table table-hover">'; for(var count = 0; count<radiation_data.length; count++) { var cell_data = radiation_data[count].split(","); table_data += '<tr>'; for(var cell_count=0; cell_count<cell_data.length; cell_count++) { if(count === 0) { table_data += '<th>'+cell_data[cell_count]+'</th>'; } else { table_data += '<td>'+cell_data[cell_count]+'</td>'; } } table_data += '</tr>'; } table_data += '</table>'; $('#datatable').html(table_data); } }); }); </script> I keep getting this error http://localhost:8000/output/tomsim_FruitDev.csv 404 (Not Found)>. How can I make my application to look into the output folder. I tried editing my settings.py file. I am not sure where to add the path to the file. -
FormSet file not uploading
I have seen this question posted several times but I am still struggling to get my formset file to upload. Things I have verified: No issues uploading the file without the child form having the primary key No issues uploading the formset if the FileField is a CharField Token ({% csrf_token %}) is being passed to the template form Form encoding type is present: enctype="multipart/form-data" Formset is being passed both, self.request.POST and self.request.FILES during post models.py class Author(models.Model): author = models.CharField(max_length=128) summary = models.CharField(max_length=1000) class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) book_file = models.FileField(upload_to='books/') forms.py class AuthorForm(forms.ModelForm): class Meta: model = Author fields = ('author', 'summary') class BookForm(forms.ModelForm): class Meta: model = Book fields = ('book_file',) BookFormSet = forms.inlineformset_factory(Author, Book, form=BookForm, fields=('book_file',)) views.py class CreateBookView(CreateView): template_name = "book_add.html" model = Author form_class = AuthorForm success_url = reverse("author_list") def get_context_data(self, **kwargs): context = super(CreateBookView, self).get_context_data(**kwargs) if self.request.POST: context["book_file"] = BookFormSet(self.request.POST, self.request.FILES) else: context["book_file"] = BookFormSet() return context def form_valid(self, form): context = self.get_context_data() book_file = context["book_file"] with transaction.atomic(): self.object = form.save() if book_file.is_valid(): book_file.instance = self.object book_file.save() return redirect(success_url) book_add.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div> {{ form }} </div> <div> {{ book_file.management_form }} {% for book in book_file.form %} {{ … -
SQL, How to create many rows at once for datetimes matching a cron expression?
Suppose you have a cron-like expression 2:30 every monday and wendsday and a period 2020.05.23 - 2021.02.02 I want to create a row for every matching time in the period 2:30 2020.05.25 (mon) 2:30 2020.05.27 (wed) How to create them in batches? (I'm on postgresql, django if it matters) -
hello , I start learning how to use django and after taping this command "python manage.py collectstatic" I got this error
the path is correct I guess this is the file setting.py -
Django display function as list in html with template tags
Given my two models, Deck and Flashcard: class Deck(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=255) class Flashcard(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) deck = models.ForeignKey(Deck, on_delete=models.CASCADE) question = models.TextField() answer = models.TextField() I want to show the details of a particular deck, e.g. list of questions and answers for that deck. So in my Deck model, I've got the following function: def list_flashcards(self): fc_list = Flashcard.objects.filter(deck=self).values_list('question', flat=True) return fc_list Now in my html template, if I use: {{deck.list_flashcards}} I get: <QuerySet ['first', 'second','third'] In other words, I get the right items, just not in the right format. How can I get this as a 'normal' list? For example, when I use... {{deck.list_flashcards.0}} <br> {{deck.list_flashcards.1}} <br> ...it works. But I won't know how many cards a user will have, and also it's of course not efficient. What I want to do is something like this: {% for fc in fc_list %} Question: {{fc}} {% endfor %} But it doesn't work - nothing appears on the website. Should I be adding this to my view for it to work? -
Django Admin: create button for foreign key of a foreign key
Sorry, for the bad title. I was not sure how to phrase it. Background: So mainly I am creating this eCommerce website which has a model called product: class Product(models.Model): name = models.CharField(max_length=80) price = models.DecimalField(decimal_places=2, max_digits=6) on_sale = models.BooleanField(default=False) sale_price = models.DecimalField(decimal_places=2, max_digits=6) short_description = models.TextField() description = models.TextField() in_stock = models.BooleanField(default=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) tags = models.ManyToManyField(Tag) def __str__(self): return self.name This model is liked to by an attribute model using foreign key as so: class Attribute(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) title = models.CharField(max_length=20) def __str__(self): return self.title finally, the attributes model is linked to by AttributesOption model using a foreign key as so: class AttributeOption(models.Model): value = models.CharField(max_length=20) attr = models.ForeignKey(Attribute, on_delete= models.CASCADE) price = models.DecimalField(decimal_places=2, max_digits=6, null=True) on_sale = models.BooleanField(default=False) sale_price = models.DecimalField(decimal_places=2, max_digits=6, null=True) short_description = models.TextField(null=True) description = models.TextField(null=True) in_stock = models.BooleanField(default=True) def __str__(self): return self.value So essentially, a product can have multiple attributes such as colour, size, type etc. Similarly, an attribute can have multiple values such as pink, blue, red, green etc. (I'll later code it so that if there is a value for on_sale, price etc. in the attribute value it will override the main product value.) Now to …