Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
show list in django without html file?
i have 2 models but i want to show name of artist in my output class Musician(models.Model): name = models.CharField(max_length=50) instrument = models.CharField(max_length=100) class Album(models.Model): name = models.CharField(max_length=100) artist = models.ForeignKey(Musician, on_delete=models.CASCADE) num_stars = models.IntegerField() i want to show musician name by HttpResponce funcction class Musician_list(Musician ,Album ): def get(self, request): qury= Musician.objects.all().values_list("name").order_by("name") return HttpResponse(qury) but this code dont show any things please help me. -
CORS Issues after adding headers field to axios when making a GET request
I am using Django REST for my API/Back end. Here is my python code: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', #'corsheaders.middleware.CorsPostCsrfMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", "http://127.0.0.1:3000" ] CORS_ORIGIN_WHITELIST = [ "http://localhost:3000", "http://127.0.0.1:3000" ] On my React JS front end: listItems = async () =>{ let fetchedItems = await axios.get("http://localhost:8000/api/shipments/list/", {headers: {accessToken: this.props.token, "Access-Control-Allow-Headers" : '*'}}); } I did not get any CORS errors when I had listItems without the headers part: listItems = async () =>{ let fetchedItems = await axios.get("http://localhost:8000/api/items/list/"}); } However, I need to pass the accessToken in the request's header. Here is the error that I am getting: Access to XMLHttpRequest at 'http://localhost:8000/api/items/list/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field accesstoken is not allowed by Access-Control-Allow-Headers in preflight response. What is the reason behind having such CORS issues, what's the best way to fix it ? -
Remove templates from Django
We are using Django solely as backend and not utilizing its template system while we are developing our code. Current set up that we have points templates to the folder where our front end is located in dist/ui. Maybe in production mode when we could build actual combined binaries and want to serve them from the server it could be useful but in the development mode it often causes issues when there are some inconsistencies in the dist/ui folder with the folder structure of the development folder. Is it possible to avoid that behavior? How could we prevent Django from loading any templates at all using it solely as a backend data layer that interacts with a database? We tried just deleting paths and/or template set ups in settings.py but it didn't help: STATIC_ROOT = os.path.join(BASE_DIR, 'ui/dist') STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'APP_DIRS': True, 'DIRS': [ os.path.join(BASE_DIR, 'ui/dist'), os.path.join(BASE_DIR, '/data'), ], 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
Filtering through relationship in views or template
I have one simple model called Product class Product(models.Model): title = models.CharField(max_length=150) def __str__(self): return self.title And one other model called ExternalProduct class ExternalProduct(models.Model): title = models.CharField(max_length=100) external_id = models.CharField(max_length=25) internal_product = models.ForeignKey( Product, on_delete=models.CASCADE, blank=True, related_name='external_products', ) price = models.IntegerField() brand = models.ForeignKey(Brand, on_delete=models.CASCADE, blank=True) image_url = models.CharField(max_length=255) product_url = models.CharField(max_length=255) store = models.CharField(max_length=50) active = models.BooleanField(default=True) class Meta: ordering = ['price'] def __str__(self): return self.title On the detailed view of the Product, I want to display the price of all ExternalProduct related to the Product. It works all fine with this view # products/views.py class ProductDetailView(DetailView): model = Product context_object_name = 'product' template_name = 'products/product_detail.html' and this template # product_detail.html {% extends '_base.html' %} {% block title %}{{ product.title }}{% endblock title %} {% block content %} <div class="book-detail"> <h2>{{ product.get_active_external_products }}</h2> </div> <div> <ul> {% for ep in product.external_products.all %} <li>{{ ep.price }}</li> {% endfor %} </ul> </div> {% endblock content %} The problem is that I just want to display the price of ExternalProduct which has active=True Been trying to solve it with a custom method in products views.py class ProductDetailView(DetailView): model = Product context_object_name = 'product' template_name = 'products/product_detail.html' def get_active_external_products(self): return self.external_products.objects.filter(active=True) And a … -
Creating a Popup Menu from a link using django, css and html
I want to know how to reference a particular section in a page in django. I know it's possible in html using a class or an id but I have tried it in django and I facing difficulties. I am creating popup menu when a linked is clicked. I have created it but how do you link it inside of the same page using Django. What I mean is how do Django does self referencing using links in a page not with models just like how html uses the class tag or the id value to link the section in the page. Thanks. https://enmascript.com/articles/2019/09/26/toggle-content-on-click-without-javascript[I want to do something like this in django still using the same html template and in the same page. ][1] -
Adding and rendering comments using django_comments
I recently started learning Python and Django and decided to make a blog as my first project, using Python 3.9.6 and Django 3.2.5. To include a comment section, I installed django_comments and followed the documentation. After migrating the new models, I tried adding a comment through the Django Admin site, but couldn't get it to render including {% render_comment_list for post %} in post_detail.html. In order to find where the issue lies, I tried adding the following django_comments template tags to see if it was a problem with render_comment_list or something else. {% get_comment_count for post as comment_count %} {{ comment_count }} It turned out the output was 0, so the reason no comments are displayed is that they are not being added. Here's the part I can't wrap my brains around: when adding a comment through the Django Admin site, choosing blog | entry as the content type and specifying the object_id, I don't get any errors, and supposedly the comment has been properly added. Also the "see in site" link for the comment takes me to the proper blog entry. Hopefully I explained myself well enough and some of you guys can spot what's probably an idiotic mistake. … -
How to delete child model data in case of on_delete=models.PROTECT?
Let assume i have two models Meeting and Call_Type and there is ForeignKey relation between them like bellow. class Meeting(SoftDeleteModel): name = models.call_type(CallType, on_delete=models.PROTECT, null=True) And:- class CallType(models.Model): type = models.CharField(max_length=256, null=False, blank=False, unique=True) Now i have deleted data from meeting table using Meeting.objects.all().delete() by mistake, and when trying delete CallType model data i get following error:- ProtectedError: ("Cannot delete some instances of model 'CallType' because they are referenced through protected foreign keys: 'Meeting.call_type'.", {<Meeting: Meeting object (1)>, <Meeting: Meeting object (2)>, <Meeting: Meeting object (3)>, <Meeting: Meeting object (4)>, <Meeting: Meeting object (5)>, <Meeting: Meeting object (6)>, <Meeting: Meeting object (7)>, <Meeting: Meeting object (8)>, <Meeting: Meeting object (9)>, <Meeting: Meeting object (10)>, <Meeting: Meeting object (11)>, <Meeting: Meeting object (12)>}) Is there is any way to delete CallType model data. Thanks in advance. Hope in here from you soon. -
send fabricjs drawing over WebSocket with django channels
I'm making a whiteboard and running it on localhost with different browser windows open. I can send shapes and textbox, but I can't figure out how to make a freedrawing appear in the canvas in the other windows. Code: HTML <button id="pencilBtn">Pencil Off</button> <canvas id="canvas"></canvas> JAVASCRIPT SENDER CODE: Click button to activate freedrawing: var pencilBtn = document.querySelector('#pencilBtn'); pencilBtn.addEventListener('click', pencilDrawing); function pencilDrawing(e){ if (e.target.textContent == 'Pencil Off'){ e.target.textContent = 'Pencil On'; canvas.freeDrawingBrush = new fabric.PencilBrush(canvas); canvas.set('isDrawingMode', true); canvas.freeDrawingBrush.width = 10; canvas.freeDrawingBrush.color = 'blue'; // Add some attributes to freeDrawingBrush canvas.freeDrawingBrush.brushtype = 'pencil'; canvas.freeDrawingBrush.user_id = user_id; canvas.freeDrawingBrush.toJSON = (function(toJSON){ return function(){ return fabric.util.object.extend(toJSON.call(this), { brushtype: this.brushtype, user_id: this.user_id }); }; })(canvas.freeDrawingBrush.toJSON); } else { e.target.textContent = 'Pencil Off'; canvas.set('isDrawingMode', false); } } MOUSE DOWN EVENT - (I know I'll need a mouse move and mouse up event, but I figured I'd start with just trying to send a drawing of a dot before anything else) canvas.on('mouse:down', (ev)=>{ if (canvas.isDrawingMode == true){ // Add another attribute to freeDrawingBrush canvas.freeDrawingBrush.obj_id = Math.random(); canvas.freeDrawingBrush.toJSON = (function(toJSON){ return function(){ return fabric.util.object.extend(toJSON.call(this), { obj_id: this.obj_id }); }; })(canvas.freeDrawingBrush.toJSON); // send freeDrawingBrush over socket whiteboardSocket.send(JSON.stringify({ 'canvas_object': { 'type': 'drawing_mouse_down', 'color': canvas.freeDrawingBrush.color, 'width': canvas.freeDrawingBrush.width, 'mouse_down_pointer': canvas.getPointer(ev), 'brushtype': canvas.freeDrawingBrush.brushtype, 'user_id': … -
Ajax funtion is through ann error Uncaught TypeError: $.ajax is not a function
I'm working on a Django project and I,m using Ajax to remove an item on a button click. I'm getting the error "Uncaught TypeError: $.ajax is not a function" every time when the button is clicked. I'm not an expert with javascript/Jquery. The way this ajax method is written has worked for me on other pages of the same product for a different function. But it is throwing error for this task Django Template <div class="menu-container"> <div class="container-heading"> <div class="row"> <span>Main Menu Section</span> </div> </div> <div class="box"> <div class="form-group"> <label for="{{ form.name.id_for_label }}"> Menu Name:<span style="color: red; font-weight: bold;">*</span> </label> <input type="text" name="menu_name" class="textinput form-control" pattern='[a-zA-Z\s]{1,250}' title="Alphabets and Spaces only" value="{{menu.name}}" required="true"> </div> {% for item in items %} <div class="row form-row"> <div id="item-{{forloop.counter}}-box" class="form-group col-md-10"> <label for="item-{{forloop.counter}}"> Item {{forloop.counter}}: </label> <input id="item-{{forloop.counter}}" type="text" name="{% if item.dishes %}{{item.slug}}{% elif item.drinks %}{{item.slug}}{% endif %}" class="textinput form-control" pattern='[a-zA-Z\s]{1,250}' title="Alphabets, Integers and Spaces only" value="{% if item.dishes %}{{item.dishes}}{% elif item.drinks %}{{item.drinks}}{% endif %}" required="true" disabled=""> </div> <div id="item-{{forloop.counter}}-box" class="form-group col-md-2"> <label for="remove-item" style="color: #fff"> . </label> <button class="menu_btn btn btn-danger delete-btn" type="button" id="remove-item-{{forloop.counter}}" onclick="removeItem({{forloop.counter}})">Remove</button> </div> </div> {% endfor %} </div> </div><div class="menu-container"> <div class="container-heading"> <div class="row"> <span>Main Menu Section</span> </div> </div> <div class="box"> … -
Filtering Posts greater than certain number of likes
I have a question about filtering Posts by Like count greater than a given number. What I want to achieve is on DJANGO SHELL when I type post.likes is greater than 10 I want to see all posts with more than 10 likes. How can I do that? Thanks models.py class Post(models.Model,HitCountMixin): likes = models.ManyToManyField(User, related_name="likes", blank=True) -
My view isn't rendering any result in the template - django
I'm working on a Django project and i'm quite the beginner so i'm really sorry if this is a basic question, my view isn't showing any result in the template, here's my view: def all_products(request): products = Product.objects.all() context = {'products': products} return render(request, 'users/home.html', context) this is the model: class Product(models.Model): title = models.CharField(max_length=255) id = models.AutoField(primary_key=True) price = models.FloatField(null=True) picture = models.ImageField(null=True) category =models.ForeignKey(Category,related_name='products',on_delete=models.SET_NULL,null=True) developer = models.ForeignKey(Developer, on_delete=models.SET_NULL, null=True) and finally this is the part of html needed: <div class="row justify-content-center" > {% for product in products %} <div class="col-auto mb-3"> <div class="card mx-0" style="width: 12rem; height:21rem; background-color: black;"> <a href="#"><img class="card-img-top img-fluid" style="width: 12rem; height:16rem;" src="{{ product.picture.url}}" alt="Card image cap"></a> <div class="card-block"> <a href="#"><h5 class="card-title mt-1 mb-0" style="color:white; font-size: 18px; font-family: 'Segoe UI';"><b>{{product.title}}</b></h5><a href="#"></a> <p class="card-text text-muted mb-1" style="color:white;">{{product.developer.title}}</p> <p class="item-price card-text text-muted"><strike >$25.00</strike> <b style="color:white;"> {{product.price}} </b></p> </div> </div> </div> <span></span> {% endfor %} </div> I also do have some product objects in my database, so where could the problem be? -
What is a robust network visualization tool that can be linked to Django web framework with a MySQL backend server?
I am trying to create a web-based protein-protein interaction network visualization graphic user interface. The web framework I am currently using is Django and my database is in MySQL. I would like the network visualization to be dynamic. That is to display the corresponding pathogen nodes based on what is selected in the drop-down list (i.e. "Select pathogen"). The drop-down list is populated by data in the MySQL database. What would be a recommended network visualization tool (preferably in Python) that can be linked to Django web framework with a MySQL backend server to display network graphs dynamically? I have previously used Networkx but I am not sure if it is able to link up with Django. -
Django Celery Periodic Task How to call Task method That is inside class
I want to send periodic mail to certain user After the user has been registered to certain platform I tried to send email using celery which works fine and Now I want django celery to send periodic mail as of now I have set the email time period to be 15 seconds. Further code is here celery.py app.conf.beat_schedule = { 'send_mail-every-day-at-4': { 'task': 'apps.users.usecases.BaseUserUseCase().email_send_task()', 'schedule': 15 } } I have my Class in this way ->apps.users.usecases.BaseUserUseCase.email_send_task here is my usecases to send email class BaseUserUseCase: def _send_email(self, user, request): self.user_instance = user self._request = request token = RefreshToken.for_user(user=self.user_instance).access_token # get current site current_site = get_current_site(self._request).domain # we are calling verify by email view here whose name path is activate-by-email relative_link = reverse('activate-by-email') # make whole url absolute_url = 'http://' + current_site + relative_link + "?token=" + str(token) # absolute_url = 'http://localhost:3000' + relative_link + "?token=" + str(token) self.context = { 'user': self.user_instance.fullname, 'token': absolute_url } self.receipent = self.user_instance.email @shared_task def email_send_task(self): print("done") return ConfirmationEmail(context=self.context).send(to=[self.receipent]) How do I call this email_send_task method am I doing right any help regarding this It is not working. -
How to create to select from year to year in html forms?
I want to user to input from this year to that and then I need to forward the list of years to django? But before this how to create that kind of input, I have found something like this, but it is not working what I need. Any ideas? <select name="yearpicker" id="yearpicker"></select> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script type="text/javascript"> let startYear = 1800; let endYear = new Date().getFullYear(); for (i = endYear; i > startYear; i--) { $('#yearpicker').append($('<option />').val(i).html(i)); } </script> -
heroku server error 505 in django work fine locally
i am trying to deploy my web app on heroku server but even on sucessfull deployment it throw server error 500 my settings.py import django_heroku from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES_DIR = BASE_DIR / 'templates' STATIC_DIR = BASE_DIR / 'static' MEDIA_DIR = BASE_DIR / 'media' STATIC_CDN = BASE_DIR / 'staticfiles' STATIC_URL = '/static/' STATICFILES_DIRS = [ STATIC_DIR, ] STATIC_ROOT = STATIC_CDN # MEDIA MEDIA_ROOT = MEDIA_DIR MEDIA_URL = '/media/' # crispy forms CRISPY_TEMPLATE_PACK = 'bootstrap4' # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' django_heroku.settings(locals()) my main projects urls.py from django.contrib import admin from django.urls import path, include from django.views.generic import RedirectView from django.conf.urls import url from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('accounts.urls')), path('accounts/', include('django.contrib.auth.urls')), url(r'^favicon\.ico$',RedirectView.as_view(url='/static/image/favicon.ico')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root = settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) everything works fine locally an idea what causing wrong here -
Django: prefix language slug in i18n_urls
I have a django-cms site, that uses i18n_patterns in urls.py. This works, urls are built like /lang/here-starts-the-normal/etc/. Now, I would like to have urls like this: /prefix-lang/here-starts.... As there will be a couple of country specific domains, this wille be like /ch-de/here-... for Switzerland/.ch domain, /us-en/here-starts.... for the states, and some more. So, when the url would be /ch-de/..., the LANGUAGE would still be de. Hope this is clear? As the content is filled with existing LANGUAGES=(('de', 'DE'), ('en', 'EN'), ...), I cannot change LANGUAGES for every domain - no content would be found in the cms, modeltranslation, only to mention those two. How can I prefix the language slug in i18n_patterns? Is it possible at all? -
filter on new updated queryset return empty queryset using ORM Django
when looping the queryset and update field in the model using save() function, then try to filter on the updated queryset , the filter result returns empty even the there are still elements in the queryset that achieve the condition. please check the code below. qs = queryset.filter(status=models.BankTransfer.STATUS_NEW) for bank_transfer in qs: bank_transfer.status = models.BankTransfer.STATUS_APPROVED bank_transfer.save() Btw when I print qs, it returns with results, but I try to get the first object by using first(), it returns None for bank_transfer in qs.filter(purpose__status='pending_completed'): bank_transfer.purpose.status = 'completed' bank_transfer.purpose.save() -
Django, less than or equal method problem, Django documentation tutorial
I am following Django documentation tutorial (part 5) and in the .../polls/ page instead of getting the questions I made, I get: No polls are available. Files look like this: The problem should be in views.py, line 15, after the line def get_queryset, but I'm not professional! views.py: from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from django.views import generic from django.utils import timezone from .models import Question, Choice # Create your views here. class IndexView(generic.ListView): template_name = 'polls/index.html' context_object_name = 'latest_question_list' def get_queryset(self): return Question.objects.filter(pub_date__lte=timezone.now()).order_by('-pub_date')[:5] class DetailView(generic.DetailView): model = Question template_name = 'polls/detail.html' def get_queryset(self): return Question.objects.filter(pub_date__lte=timezone.now()) class ResultsView(generic.DetailView): model = Question template_name = 'polls/results.html' def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice." }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results',args=(question.id,))) index.html: {% load static %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="{% static 'polls/style.css' %}"> <title>The index page</title> </head> <body> {% if lastest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are … -
Django Customized Forgot Password error (custom user model)
looking for help! I am not that experienced writing Python/Back-end code even though I am improving. In development/localserver I am trying to create a customized password reset form... but I got the following error after I submitted the email when testing the form and never received and email with the link: save() got an unexpected keyword argument 'use_https' My custom Forgot Password Form class PrivateForgotPasswordForm(forms.ModelForm): helper = FormHelper() helper.add_input(Submit('page_userForgotPassword_content_form_button_submit', static_textLanguage['global_button_submit'], css_class='global_component_button')) class Meta: model = PrivateUser fields = ['email'] widgets = { 'email': forms.EmailInput(attrs={ 'id': 'page_userForgotPassword_content_form_input_email', 'maxlength': '254', 'class': 'global_component_input_box'} ) } def __init__(self, *args, **kwargs): super(PrivateForgotPasswordForm, self).__init__(*args, **kwargs) self.helper.form_id = 'page_userForgotPassword_content_form' self.helper.form_method = 'post' self.helper.form_action = '' self.helper.form_class = 'page_userForgotPassword_content_form' My custom Forgot Password View class UserForgotPasswordView(auth_views.PasswordResetView): with open(str(settings.BASE_DIR) + "/frontend/static/frontend/languages/emails/EN/email_footer__main.json", "r") as temp_file_email_footer_main: email_footer_main_data = json.load(temp_file_email_footer_main) with open(str(settings.BASE_DIR) + "/frontend/static/frontend/languages/emails/EN/email_user_forgotPassword.json", "r") as temp_file_email_forgot_password: email_forgot_password_data = json.load(temp_file_email_forgot_password) extra_email_context = { 'email_footer_static_json_text': email_footer_main_data, 'email_static_json_text': email_forgot_password_data, 'static_json_text': static_textLanguage, 'static_json_textGlobal': static_textGlobal} html_email_template_name = '../frontend/templates/frontend/templates.emails/template.email_user_forgotPassword.html' from_email = 'support@xyz.com' subject_template_name = 'Reset password' template_name = '../frontend/templates/frontend/templates.user/template.page_forgotPassword.html' form_class = PrivateForgotPasswordForm success_url = reverse_lazy('password_reset_done') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context = { 'forgot_password_form': PrivateForgotPasswordForm(), 'email_subject': self.email_forgot_password_data['emailSubject'], 'static_json_text': static_textLanguage, 'static_json_textGlobal': static_textGlobal} return context -
Django - Migrating data inside tables for smooth release
I am using Django Rest Framework for backend development, where I have set up 2 environments. I have split settings files as required and both the environments have different DBs which are working fine, I am using Zappa(AWS lambda) for deploys, I was wondering is there an elegant way of migrating data(not models but data inside models say a few config changes) than preparing PostgreSQL DB rollouts, Could not find much on the internet, so asking here. Please let me know if there are any questions. -
What is the purpose of parameter_name in django SimpleListFilter?
What is the purpose of parameter_name in django SimpleListFilter ? It still works if parameter_name is set to empty string. class EmailFilter(SimpleListFilter): title="Email Filter" parameter_name="user_name" def lookups(self,request,model_admin): return ( ('has_email','Has Email'), ('no_email','No Email') ) def queryset(self, request,queryset): if not self.value(): return queryset if self.value() =='has_email': return queryset.exclude(user__email='') if self.value() =='no_email': return queryset.filter(user__email='') -
How to implement edit-form with Django formset?
I implemented a django-form with a formset. When I create a new object it works. But I faced to a problem with editing form when I don't change formset data (only data outside formset). Formset raises errors: id requeired. If I mark formset fields to delete and then add new fields it works too. Please, explain me what's going wrong and how to solve this problem. Thanks! My formset: IngredientsFormSet = forms.inlineformset_factory( Recipe, RecipeIngredientsDetails, fields="__all__", can_delete=True, min_num=2, max_num=50, extra=0, ) And my view-function: def recipe_edit(request, recipe_id=None): if recipe_id: recipe = get_object_or_404(Recipe, id=recipe_id) else: recipe = Recipe() if request.method == "POST": form = RecipeCreateForm(data=request.POST, files=request.FILES) formset = IngredientsFormSet(data=request.POST, prefix=INGREDIENT_FORMSET_PREFIX) if form.is_valid() and formset.is_valid(): recipe = form.save(commit=False) recipe.author_id = request.user.id recipe.save() form.save_m2m() formset.instance = recipe formset.save() return redirect(reverse_lazy("index")) context = {"form": form, "formset": formset} return render(request, template_name="recipe-create.html", context=context) form = RecipeCreateForm(instance=recipe) formset = IngredientsFormSet( instance=recipe, prefix=INGREDIENT_FORMSET_PREFIX, ) context = { "form": form, "formset": formset, } return render(request, context=context, template_name="recipe-create.html") -
Why does stripe card element not load up when using django stripe?
Hi I've been trying to learn how to build an ecommerce site and am getting stuck with the Django Stripe integration for a custom pay flow. I can get the pre built checkout to work but can't for custom pay flow. Stripe seems to have updated the code on their docs a few months ago so when I try to look up tutorials, they all don't seem to have the same code and I can't seem to figure out how to get it to work. I'm self taught and just a beginner/intermediate maybe so might be missing something obvious. I'm using the code from this page https://stripe.com/docs/payments/integration-builder and trying to convert it into Django. This is my views.py from django.shortcuts import render import stripe from django.http import JsonResponse import json # Create your views here. from django.views import View stripe.api_key = "xxxxxxxxx" class StripeIntentView(View): def post(self, request, *args, **kwargs): try: intent = stripe.PaymentIntent.create( amount=2000, currency='usd' ) return JsonResponse({ 'clientSecret': intent['client_secret'] }) except Exception as e: return JsonResponse({'error':str(e)}) def payment_method_view(request): return render(request, 'custom-landing.html') This is my urls.py from django.contrib import admin from django.urls import path from products.views import payment_method_view,StripeIntentView urlpatterns = [ path('admin/', admin.site.urls), path('custom-landing/', payment_method_view, name='custom-landing-page'), path('create-payment-intent/', StripeIntentView.as_view(), name='create-payment-intent'), ] … -
Very confusing question regarding WEB dev
I have gotten the following questions which is so ambiguous, does anybody knows the answer? You create a static web site that simply consists of several HTML files on a web server. What possible difficulty might you run into with this setup as you continue to maintain your site? a. Updating URL design would require many edits throughout the site b. All of these c. Hyperlinks between pages of the site could become inconsistent d. Changes to the site’s look and feel would need to be made in many files -
Crontab Django Management command seems to start but nothing happens
I have defined a django management command that imports some data into my application database. I run it using a crontab. Sidenote: everything is inside a docker container. This command works perfectly when I use it manually in my container's shell. However, when crontab tries to run it, nothing happens. My crontab line is the following : * * * * * nice -n 19 /usr/local/bin/python3 /code/manage.py my_command "a string argument for my command" # a comment to find the cron easily (I put my code into /code because it seemed a good idea at the time.) I know that crontab calls my command, because /var/log/syslog displays when it is executed. I cannot fathom the reason why nothing happens. As a test in the "handle" method of my command, I wrote print("handling command") as the first line then added >> /code/cron.log at the end of my crontab line. The text didn't appear in the file. Any idea ?