Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
create update view and implement it list view
i want to implment updateview in my list view but i dont know what is wrong with my update view and then prepopulate it with values of model that it is updating thanks in advance here is my model.py from django.db import models from django.conf import settings from django.core.validators import MinValueValidator, MaxValueValidator # Create your models here. class Item(models.Model): distributor=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) Item_name=models.CharField(max_length=40) max_order=models.PositiveIntegerField(default=1,validators=[MinValueValidator(1),]) stock=models.PositiveIntegerField() availability=models.BooleanField(default=True) price_per_item=models.DecimalField(validators=[MinValueValidator(1),],max_digits=6, decimal_places=2) discount=models.DecimalField(validators=[MinValueValidator(1),MaxValueValidator(100)],max_digits=4, decimal_places=2) objects = models.Manager() class Meta: ordering = ('item_name',) def __str__(self): return self.item_name here is my form.py from django.forms import ModelForm from .models import Item from django import forms class ItemForm(ModelForm): class Meta: model = Item fields = ('Item_name','stock','price_per_item','discount','max_order',) here is my views.py with update view and list view only create view not here from django.shortcuts import render,HttpResponse,get_list_or_404 from django.views.generic.edit import CreateView,UpdateView from django.views.generic.list import ListView from .models import Item from .forms import ItemForm from django.contrib.auth.mixins import LoginRequiredMixin from django.db.models.functions import Lower class vendorList(LoginRequiredMixin,ListView): model = Item # paginate_by=50 template_name = "vendors/Item_list.html" def get_context_data(self, **kwargs): context = super(vendorList, self).get_context_data(**kwargs) context['update_form'] = ItemForm return context def get_queryset(self): return Item.objects.filter(distributor=self.request.user).order_by(Lower('Item_name').asc()) class ItemUpdate(LoginRequiredMixin,UpdateView): model=Drug form_class = ItemForm template_name = 'create_Item.html' success_url = 'vendor/list' #get object def get_object(self, queryset=None): obj = Item.objects.get(id=self.kwargs['id']) return obj urls.py urlpatterns=[ url(r'^add/$',create_Item.as_view(),name="add_Item"), … -
Django 'Sort By:' functionality
I'm very new to Django and am working on an ecommerce store project. I'm attempting to integrate 'Sort By:' functionality into my product list view such as you would see on Amazon. Could someone possibly give me the general direction on how to go about implementing this? I've tried locating resources online and cannot find a thing. Any help would be appreciated! -
NoReverseMatch Error Django
I have the following model: class UserPlaceReview(models.Model): place = models.ForeignKey(PlaceReview) review = models.TextField() def __str__(self): return self.review class PlaceReview(models.Model): name = models.CharField(max_length=150) location = models.CharField(max_length=250) image = models.ImageField(upload_to = image_upload_location,null=True, blank=True) category = models.ForeignKey(Categories) slug = models.SlugField() timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.name def get_absolute_url(self): return reverse("categories:detail", kwargs={"slug": self.slug}) In my main urls.py I have the following url: url(r'^categories/', include('places.urls', namespace='categories')), and in my app urls.py I have the following url: url(r'^(?P<slug>[\w-]+)/review/$', user_place_review, name='user_review'), In a template I am trying to do something like this which gives me a no reverse match error: <a class="btn btn-primary btn-lg" href="{% url 'categories:user_review' %}">Write A Review!</a> The view linked to the url is : def user_place_review(request,slug): place = PlaceReview.objects.get(slug=slug) form = UserPlaceReviewForm(request.POST or None) if form.is_valid(): instance = form.save(commit=False) review = form.cleaned_data['review'] instance.place = place instance.review = review instance.save() return redirect('/') context = { "form": form, } return render(request,"places/user_review.html", context) I am unable to find the cause of the error. -
Django model choice field from another model instance
In my models.py, I have two classes, ChoiceList and SampleModel as below class ChoiceList(models.Model): choice=models.CharField(max_length=15) class SampleModel(models.Model): CHOICELIST=ChoiceList.objects.all() name=models.CharField(max_length=15) your_choice=models.CharField(max_length=15,choices=ChoiceList) I need to add your_choice field data only from ChoiceList instances. Can I add data in that way ? When I doing this way, I got error as django.db.utils.OperationalError: no such table: rest_api_ChoiceListCan anyone solve the problem ? -
how to change background color in the django without using css and only html?
I wanted to change the background image without using the css code and only html code. Previously, there was no html tag.. I tried to add one. The code works however there is no change in colour . here is a code for base.html {% load bootstrap3 %} {% bootstrap_css %} {% bootstrap_javascript %} {% block bootstrap3_content %} {% block additional_styles %} <html> <head></head> <body {% block bg %}background='download1.jpg' class="base_bg_class"{% endblock %}> <div class="container"> <nav class="navbar navbar-default"> <div class="navbar-header"> <a class="navbar-brand" href="{% url 'reviews:review_list' %}">Winerama</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="{% url 'reviews:wine_list' %}">Wine list</a></li> <li><a href="{% url 'reviews:review_list' %}">Home</a></li> </ul> <ul class="nav navbar-nav navbar-right"> {% if user.is_authenticated %} <li><a href="{% url 'reviews:user_review_list' user.username %}">Hello {{ user.username }}</a></li> <li><a href="{% url 'reviews:user_recommendation_list' %}">Wine suggestions</a></li> <li><a href="{% url 'auth:logout' %}">Logout</a></li> {% else %} <li><a href="{% url 'auth:login' %}">Login</a></li> <li><a href="/accounts/register">Register</a></li> {% endif %} </ul> </div> </nav> <h1>{% block title %}(no title){% endblock %}</h1> {% bootstrap_messages %} {% block content %}(no content){% endblock %} </div> {% endblock %} {% endblock %} </body> </html> -
Best way to schedule email reports to users in Django
So this question is focused more around best practice and advice for Django. Essentially, I want to schedule email reports on Django to be triggered on two events: Weekly report email with some stats, news etc Report triggered on event in a system (i.e. a save on a model) Should this be done directly in Django through scheduled tasks? Or are there any other tools one could use? -
Fullcalendar.js calendar disappears in Angular
I am using FullCalendar.js in one of my web applications. It appears on the app's landing page when the page first loads a base template with an angular script. I initiate the calendar in a document.ready function. If I navigate to a different angular controller, and than navigate back to the home page without a page reload the calendar does not show up. Relevant HTML <head> <title>Ample Admin Template - The Ultimate Multipurpose admin template</title> <!-- Meta --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <!-- JS --> <script src="/static/js/jquery/dist/jquery.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-route.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-sanitize.min.js"></script> <script type='text/javascript' src="/static/js/mobile_angular/mobile-angular-ui.min.js"></script> <script type='text/javascript' src="/static/js/mobile_angular/mobile-angular-ui.gestures.min.js"></script> <script src="https://cdn.rawgit.com/Luegg/angularjs-scroll-glue/master/src/scrollglue.js"></script> <script src='/static/angular-upload/angular-upload.min.js'></script> <script src='/static/js/ui-bootstrap.js'></script> <script type='text/javascript' src="/static/js/dealer_bundle.js"></script> <script> $(document).ready(function () { setTimeout(function () { var calendar = $('#calendar'); calendar.fullCalendar({ dayClick: function (date, jsEvent, view) { $('#my-event').show(400); $('.calendar-overlay').show(500); $('#event-date-title').html('Add Event for ' + date.format()); window.holiday = date.format(); } }); }, 1000); }); function closeHolidayWindow() { $('#my-event').hide(400); $('.calendar-overlay').hide(500); } </script> <!-- CSS --> <link href="/static/css/bootstrap.min.css" rel="stylesheet"> <link href="/static/css/animate.css" rel="stylesheet"> <link href="/static/css/style.css" rel="stylesheet"> <link href="/static/css/colors/blue-dark.css" id="theme" rel="stylesheet"> <link href="/static/css/morris.css" rel="stylesheet"> <link href="/static/css/sidebar-nav.min.css" rel="stylesheet"> <link href="/static/css/dealer_base.css" rel="stylesheet"> <link rel="stylesheet" href="/static/css/fullcalendar.css"> </head> <!-- Calendar Popup --> <div class="calendar-overlay" style="position: fixed; top: 0; left: … -
Django endless pagination forget my js
I would like to make an endless pagination. I found this article : https://simpleisbetterthancomplex.com/tutorial/2017/03/13/how-to-create-infinite-scroll-with-django.html It works, when I scroll down, new HTML code is loaded, so I have new content. However my HTML works with javascript and It seems that the endless pagination forget my javascript. Any idea why ? Thanks -
how to add background image in django template
I am having problem in adding background image in my django project.The code for base.html where i want to add the syntax is given below.Can you please help. {% load bootstrap3 %} {% bootstrap_css %} {% bootstrap_javascript %} {% block bootstrap3_content %} <div class="container"> <nav class="navbar navbar-inverse"> <div class="navbar-header"> <a class="navbar-brand" href="{% url 'reviews:review_list' %}">Winerama</a> </div> <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="{% url 'reviews:wine_list' %}">Wine list</a></li> <li><a href="{% url 'reviews:review_list' %}"> <span class="glyphicon glyphicon-home"></span> Home</a></li> </ul> <ul class="nav navbar-nav navbar-right"> {% if user.is_authenticated %} <li><a href="{% url 'reviews:user_review_list' user.username %}"> <span class="glyphicon glyphicon-user"></span> Hello{{ user.username }}</a></li> <li><a href="{% url 'reviews:user_recommendation_list' %}"> <span class="glyphicon glyphicon-glass"></span> Wine suggestions</a></li> <li><a href="{% url 'auth:logout' %}"> <span class="glyphicon glyphicon-log-out"></span> Logout</a></li> {% else %} <li><a href="{% url 'auth:login' %}"> <span class="glyphicon glyphicon-log-in"></span> Login</a></li> <li><a href="/accounts/register"> <span class="glyphicon glyphicon-user"></span>Register</a></li> {% endif %} </ul> </div> </nav> <h1>{% block title %}(no title){% endblock %}</h1> {% bootstrap_messages %} {% block content %}(no content){% endblock %} </div> {% endblock %} -
How to implement an UpdateView Class Based View
I'm building an app where businesses can upload their local shop with a bunch of information. Currently, there is a form which is working but I'd like to implement an UpdateView in order for businesses to update their information whenever they want. Here is my model.py: class Business(models.Model): owner = models.OneToOneField(User, null=False) name = models.CharField(max_length=75) logo = models.ImageField(null=True, blank=False, upload_to=upload_location) players = models.CharField(max_length=4, choices=PLAYERS_CHOICES, default='2-4') average_price = models.IntegerField() number_games = models.IntegerField() city = models.CharField(max_length=25, choices=CITY_CHOICES) address = models.CharField(max_length=200) website = models.CharField(max_length=300) description = models.TextField(max_length=1000, null=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) slug = models.SlugField(null=True, blank=True) Notice that I'm using a OneToOneField, since one owner can only have one business within the site. My views.py for the form: class BusinessCreateView(LoginRequiredMixin, CreateView): form_class = BusinessCreateForm login_url = '/login/' template_name = 'business/form.html' success_url = '/' def form_valid(self, form): instance = form.save(commit=False) instance.owner = self.request.user return super(BusinessCreateView, self).form_valid(form) And here is my forms.py: class BusinessCreateForm(forms.ModelForm): class Meta: model = Business fields = [ 'name', 'logo', 'players', 'average_price', 'number_games', 'city', 'address', 'website', 'description', ] I've been checking the documentation and I haven't been able to implement an UpdateView. How could I do it? Thank you so much in advance! -
Can't understand what queries using through model do in Django
I have the following models: class Goal(Model): id = UUIDField(primary_key=True, default=uuid.uuid4, editable=False) # title of the goal title = CharField(verbose_name=_('Name'), max_length=256) children = ManyToManyField('self', through='DecompositionGoal', symmetrical=False) class DecompositionGoal(Model): id = UUIDField(primary_key=True, default=uuid.uuid4, editable=False) parent = ForeignKey(Goal, related_name='related_src') child = ForeignKey(Goal, related_name='related_dst') is_accepted = BooleanField(default=False) For a given goal I'm trying to find all children goals that are accepted. I ended up with goal.children.filter(related_dst__is_accepted=True). But just for curiosity what does the following selects: goal.children.filter(related_src__is_accepted=True)? Can somebody explain all this works when using through model? -
All django lists are appears twice in my templates for all templates
In my django template whenever I execute a for loop in any of my project app templates it displays the whole page twice This is my base.html **{% load staticfiles %} {% load crispy_forms_tags %} <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <link rel="icon" type="png" sizes="192x192" href="{% static 'media/icon-0.png' %}"> <title>Virgin city - {% block title %}{% endblock %}</title> <link rel="stylesheet" type="text/css" href="{% static 'css/bootstrap.min.css' %}"> <!-- Bootstrap theme --> <link rel="stylesheet" type="text/css" href="{% static 'static/css/bootstrap-theme.min.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'static/css/theme.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'static/css/main.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'static/css/base.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'css/base.css' %}"> </head> <body> {% include 'navbar.html' %} <div id="content"> {% if messages %} <ul class="messages"> {% for message in messages %} <li class="{{ message.tags }}"> {{ message|safe }} <a href="." class="close">✖</a> </li> {% endfor %} </ul> {% endif %} {% block content %} {% endblock %} </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <script src=" http://cdn.jsdelivr.net/jquery.cookie/1.4.1/jquery.cookie.min.js "></script> <script> var csrftoken = $.cookie('csrftoken'); function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $(document).ready(function(){ {% block domready %} {% … -
Make django ajax view return a file
I'm having trouble when trying to return a file through a view. Working case: User submits a form, I instanciate an excel file from these values and return it to the user. After submitting, user got a popup inviting him to download the file. No problem. Not working case: User selects values from a jstree and submits them with ajax. Again I instanciate an excel file and return it. However, though everything goes fines (no server error, success function triggered in ajax), nothing happens. The file is created this way: response = HttpResponse(content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename="export.xls"' response = comparaison(response, wb, ws_same, ws_diff, tree_left, tree_right) wb.save(response) return response It goes fine in first case but not in second. I've also tried to find a workaround by saving the file on the server for a short time and redirect user to its location in this way. wb.save('export.xls') return redirect(path_to_export_xls) It also gives no error but triggers nothing. I've no idea of what I'm missing, the only difference I see is that in the second case, file is not generated from syncronous post submit but I cant why it should be an issue. Thanks in advance for any suggestion. -
How to use two different email addresses for emails sending?
I have a Django project which has two domains. domain1.com domain2.com I use Sites application to differ between those two addresses like: <h1>Welcome to {% if site.id==1 %}Domain1{% else %}Domain2</h1> I want to be able to send messages from both emails: send_email(user, 'domain1@gmail.com' if site.id==1 else 'domain2@gmail.com', message...) I tried add from_email to EmailMessage but it doesn't work. Sender is 'domain1@gmail.com'. mail = EmailMessage(subject, message, from_email='domain2@gmail.com', to=[user_email]) mail.send() I have only one settings.py so I can set probably only one SMTP. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'domain1@gmail.com' EMAIL_HOST_PASSWORD = 'pswd' Do you know how to make it work? -
Add non-template HTML to crispy forms layout
I have a dynamic formset (using crispy forms) to set prices for objects. I need to display the name of these objects to users, so they know which object they're setting the price for. However, these names are chosen by the users themselves in a different form. It seems most obvious to use the HTML class for this (inside Layout), but that's for rendering Django templates. Letting users add template code leads to security issues. One solution I thought of is manually "escaping" it first, e.g. by wrapping it in a {% verbatim XXXXXX %} tag, with XXXXXX some securely random string, or by replacing any curly brace by its HTML character code. But both of these solutions seem pretty hacky and prone to mistakes and thus security issues. Is there a cleaner way to insert pure HTML into a crispy forms Layout? -
Rendering Django Template Blocks in Specific Places on Page
I am trying to achieve something in Django Templating Language without knowing whether it is possible (without resorting to JS or something like that). I have the following code (from Django-Oscar) which renders 3 blocks of promotions on the main page: {# Render promotions #} <div id="promotions"> {% for promotion in promotions_page %} {% render_promotion promotion %} {% endfor %} </div> These three blocks are Single Item, Products and New Arrivals. The code above appears in the layout.html which is essentially responsible for rendering the entire layout of the main page. The problem is that as soon as soon as Django encounters this code, it renders all of the promotions there one after another. I, however, would like to chose where on the page I place them. What's more, I do not believe that I have much flexibility in how I render them, read - I do not want to change the Oscar e-commerce and rendering code unless absolutely necessary. Since I have access to individual templates for Single Item, Products and New Arrivals promotions, I tried creating DTL blocks there and then calling those blocks at proper places on the layout.html. However, that does not work. What is a … -
Django get keys, values from dict and add them to query
I'm wondering if there is a good way to achieve this: class Notification(models.Model): target_clients_query = JSONField(blank=True) I have a model with a JSONField (I could change this). It keeps the query of Client objects that will receive a Notification. class Client(models.Model): user = models.OneToOneField(User, null=False, related_name='client_profile', db_index=True) phone = models.CharField(max_length=15, db_index=True, blank=True) cart = models.ForeignKey(Cart, null=True, blank=True, related_name='client', db_index=True) profile_picture = models.ImageField(null=True, blank=True, upload_to=get_uuid_client_image) facebook_user_id = models.CharField(blank=True, max_length=250) email_order_notifications = models.BooleanField(default=True) current_sector = models.ForeignKey("Sector", null=True) I would like to save the query data in the JSONField and then, when I process the Notification objects, get the corresponding clients to send notification to: from datetime import datetime from django.core.management.base import BaseCommand from app.misuper.models import Notification class Command(BaseCommand): """ Sends notifications to users """ def handle(self, *args, **options): actual_time = datetime.today() notifications_to_send = Notification.objects.filter(sent=False, programmed_date__lte=actual_time.today()) for notification in notifications_to_send: if notification.target_client: notification.send_notification() else: clients_query = notification.target_clients_query for key, value in clients_query: pass # Query the Client's model with the filters in the clients query dict -
Django iterate on static files in template
I'm new to Django and I'm struggling with this : in my template, I want to iterate on an array defined in my view, add '.png' to the end of each value so I can use them as src value for an <img> tag that I create while iterating. Here's my code : <table> <tr> {% for iter in array %} {% with 'path/to/images/'|add:iter|add:'.png' as myImg %} <td><img src="{% static myImg %}" alt=""></td> {% endwith %} {% endfor %} </tr> </table> When I print myImg, its value is only '.png', without the iter value. Maybe I can't use with tag inside a loop ? If so, how can I can concatenate my path, filename and extension ? Thank's in advance -
Syntax error in **kwargs in django while trying to print object in shell
I am trying to print the object in the powershell. But I am getting a syntax error. class RestaurantDetailView(DetailView): model = Restaurant def get_context_data(self, *args, **kwargs) context = super(RestaurantDetail, self).get_context_data(*args, **kwargs) print (context) return context the shell is giving me an error: def get_context_data(self, *args, **kwargs) ^ SyntaxError: invalid syntax -
How to order a list with Django's Paginator?
Here we go: I have an object's list that I retrieve from my Database and I sort it by a field. Then I paginates the result list, by getting an specific page. Problem: The result list is sorted by my field, but its done only by page, NOT THE WHOLE LIST. Example: [1,8,5,12,7,3] I get: Page 01: [1,5,8] Page 02: [3,7,12] But I want Page 01: [1,3,5] Page 02: [7,8,12] Here is my code: queryset = Event.objects.filter(establishment__category_id__exact=cat).order_by('-date_begin') paginator = Paginator(queryset, 3) try: events = paginator.page(page) except PageNotAnInteger: events = paginator.page(1) except EmptyPage: events = [] return events -
Django Multipart Image Upload: 'NoneType' object has no attribute 'read'
While uploading an ImageFile to a Django REST backend I am encountering the following error: Internal Server Error: /user/addimage/ Traceback (most recent call last): File "/home/neuron/genie2_env/lib/python3.4/site-packages/django/core/handlers/exception.py", liner response = get_response(request) File "/home/neuron/genie2_env/lib/python3.4/site-packages/django/core/handlers/base.py", line 187,e response = self.process_exception_by_middleware(e, request) File "/home/neuron/genie2_env/lib/python3.4/site-packages/django/core/handlers/base.py", line 185,e response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/neuron/genie2_env/lib/python3.4/site-packages/django/views/decorators/csrf.py", line 5w return view_func(*args, **kwargs) File "/home/neuron/genie2_env/lib/python3.4/site-packages/django/views/generic/base.py", line 68, w return self.dispatch(request, *args, **kwargs) File "/home/neuron/genie2_env/lib/python3.4/site-packages/rest_framework/views.py", line 489, in dh response = self.handle_exception(exc) File "/home/neuron/genie2_env/lib/python3.4/site-packages/rest_framework/views.py", line 449, in hn self.raise_uncaught_exception(exc) File "/home/neuron/genie2_env/lib/python3.4/site-packages/rest_framework/views.py", line 486, in dh response = handler(request, *args, **kwargs) File "/home/neuron/genie2/user_profiles/views.py", line 92, in post profile_stored = file_system_instance.save('profile_' + data['first_name'] + ".jpg", request.FIL) File "/home/neuron/genie2_env/lib/python3.4/site-packages/django/core/files/storage.py", line 54, e return self._save(name, content) File "/home/neuron/genie2_env/lib/python3.4/site-packages/django/core/files/storage.py", line 351,e for chunk in content.chunks(): File "/home/neuron/genie2_env/lib/python3.4/site-packages/django/core/files/base.py", line 81, in s data = self.read(chunk_size) File "/home/neuron/genie2_env/lib/python3.4/site-packages/django/core/files/utils.py", line 16, in> read = property(lambda self: self.file.read) AttributeError: 'NoneType' object has no attribute 'read' [01/Aug/2017 14:14:22] "POST /user/addimage/ HTTP/1.1" 500 18686 My View: class AddImage(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def post(self, request): user_serialized = ContactNumberUserSerializer(instance=self.request.user) data = user_serialized.data instance = ContactNumberUser.objects.get(contact=data['contact']) profile_img_instance = ImageFile(request.FILES.get('profile_pic')) file_system_instance = FileSystemStorage(location=settings.MEDIA_ROOT) instance.profile_pic = file_system_instance.save('profile_' + data['first_name'] + ".jpg", profile_img_instance) instance.save() return Response(status=status.HTTP_200_OK) Am I doing it completely wrong somehow? If … -
Django formset: show forms
I have the following models: class DecompositionGoal(Model): id = UUIDField(primary_key=True, default=uuid.uuid4, editable=False) parent = ForeignKey(Goal, related_name='related_src') child = ForeignKey(Goal, related_name='related_dst') In Goal model there is a boolean field is_quantitative. For the given parent I want to change is_quantitative field for each child. Don't know how to apply inlineformset for this. What are the ways of accomplishing this task? -
Django app.py removes underscore in Config
PEP 8 says "Modules should have short, all-lowercase names. Underscores can be used in the module name if it improves readability. Python packages should also have short, all-lowercase names, although the use of underscores is discouraged." I am working on an educational program which could, ultimately, have many lessons. Sometimes one app could deliver thousands of lessons (i.e. spelling), but still, there could be many apps. Underscores in lower case names for readability seems essential. When I use an underscore in an app name, such as clockwise_counter, "python manage.py startapp clockwise_counter" removes the underscore in constructing the class name in apps.py. The class name becomes "class ClockwiseCounterConfig(AppConfig): name = 'clockwise_counter'" This caused me a lot of confusion until I learned to copy the apps.py class name into the INSTALLED_APPS section of settings.py by removing the underscore. My Questions are: Why are the underscores discouraged in PEP 8? Is there really a good reason or was it just personal preference sometime in the past. Am I likely to have problems using underscores in app names for readability now or in the future? -
Djanjo/Python: passed variable not working as expected in function
I'm trying to get the following function working in my views.py file. I'm passing in a keyword to search for (the_Term), if I do a print statement, I can see that the variable has been passed correctly however, it is not getting passed to the API call (q=the_Term). If I hard code my keyword (q="my keyword") the function works properly. What am I doing wrong? def search_by_keyword(self,the_Term): DEVELOPER_KEY = "MY API KEY" YOUTUBE_API_SERVICE_NAME = "youtube" YOUTUBE_API_VERSION = "v3" youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey= DEVELOPER_KEY) search_response = youtube.search().list(q=the_Term, part="id,snippet", maxResults=1).execute() videos = [] for search_result in search_response.get("items", []): if search_result["id"]["kind"] == "youtube#video": videos.append((search_result["id"]["videoId"])) return 'https://www.youtube.com/watch?v=' + videos[0] -
Django : Where to write the management form data?
This might be the stupidest question but can anyone tell me where we are supposed to write the management_form data while dealing with formsets?...As in do we write it in views.py or forms.py...Thank you!