Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to render django forms retrieved by an ajax call jquery
i have a formset and need to fill it with data retrieved by an ajax call, all work fine, but the html does not show the content inside the input despite having the right value: <input type="text" name="formsets-2-0-cantidad" value="355" class="w3-input w3-border" placeholder="Cantidad" required="" id="id_formsets-2-0-cantidad"> all render properly if accessed through the endpoint and not by ajax, this is the jquery code: sendAjaxRequest_and_UpdatePage() { var el = this.buttonAddFF; $.post("getProduccionFormset", { csrfmiddlewaretoken: $("[name='csrfmiddlewaretoken']").attr("value"), //revisar si es mejor hacer .val(), y si no trae problemas de seguridad enviarlo asi producto: $("#id_producto_name").val(), cantidad: $("#id_cantidad").val() }, function(data, status) { $('#PredefinedAmountModalForm').hide(); return addFormset(el, $(el).attr("to"), 'pickPFormset', data); }); } and here is how the data is added: $(formset).removeAttr('id').insertAfter($(fformset.find('.dynamic-formset:last'))).children('.hidden').removeClass('hidden'); -
Cannot delete or rename field in a model without errors (unknown field specified)
I have no idea what's going wrong, over the last few days, I've have made quite a few changes to the overall structure of my database, including adding and deleting fields and have tried making migrations this evening. In one of my models (projects), I previously had a field named 'fk_user' which was foreign key field to the User. It worked fine but I decided it was no longer needed and deleted it at some point, however now i am getting the error django.core.exceptions.FieldError: Unknown field(s) (fk_user) specified for projects I've had this error several times in the past caused by deleted fields and have spent many hours searching for solutions only to give up in frustration and create a new database to solve the problem, which isn't an issue at this stage. This time however, despite clearing all pycache files, creating a new empty database and referencing this new database in the settings - it is giving me the same error when I try to run migrations. The only thing that solves it is adding any field to the model with the name 'fk_user', if I do this I can successfuly run migrations and migrate. However even after this, … -
I want to make it so that each product will have a link, and the link will link to a page with the product's info
I am working on a django project. I have this class in the models.py file: class Product(request): name = models.CharField(max_length=255) cost = models.FloatField(max_length=255) info = models.CharField(max_length=2000) Here is my views.py file: from django.shortcuts import render from django.http import HttpResponse from .models import Product def index(request): products = Product.objects.all() return render(request, 'index.html', {'products': products}) # I know the below is incorrect, but I don't know how to correct it. def information(request): info = Product.objects.all() return HttpResponse(info[products.index(product)].info) Here is my index.html file: {% for product in products %} <l1>{{product.name}} ${{ product.price }}</li> {% endfor %} I want to make it so that each product will have a link, and the link will link to a page with the product's info. How can I dynamically do this? Thanks. -
Docker compose, Django: Serving static files using Nginx not working correctly
I've been trying to set up a Docker container stack to deploy my Django web app. I added a volume to the Nginx container mapping the server static folder to /static: volumes: - ./server/static/:/static And then I added the /static/: location to my nginx configuration: *location /static/ { autoindex off; root /static/; }* Everything else works fine, once I run "docker-compose up" my webserver is accessible through localhost:8000 but my static files are not visible. I'm not really sure why is not working correctly. Currently, this is my folder structure: -ProjectName -docker -django -Dockerfile -nginx -Dockerfile -nginx.conf -.env -server -apps -main -static <-- Here are all the files I want to serve -templates -manage.py -docker-compose.yml -Pipfile -Pipfile.lock -.gitignore docker-compose.yml version: '3' services: django: build: context: . dockerfile: docker/django/Dockerfile volumes: - ./server:/server expose: - 8000 command: gunicorn -w 4 main.wsgi -b 0.0.0.0:8000 env_file: docker/.env nginx: build: context: . dockerfile: docker/nginx/Dockerfile volumes: - ./server/static/:/static ports: - 8000:80 depends_on: - django django/Dockerfile: FROM python:3.8 ENV PYTHONUNBUFFERED 1 RUN pip install pipenv WORKDIR /server COPY Pipfile Pipfile.lock ./ COPY ./server . RUN pipenv install --system --deploy nginx/Dockerfile: FROM nginx RUN rm /etc/nginx/conf.d/default.conf COPY ./docker/nginx/nginx.conf /etc/nginx/conf.d nginx/nginx.conf: upstream django_app { server django:8000; } server { … -
How to add a countdown timer as a user field in django?
I want for every user on an application that they have a field with a certain time, which gets used up when using the website. So if you have an account with 10 hours, there is a field that counts down those 10 hours. Is there any existing way how to do this and have it continuously update? -
Is it possible to get multiple sets of rows, each containing a limited number of rows, filtered by a column in a table in Django/SQL?
Sorry the question is so confusing, I couldn't find a way to word it better. This is better explained with an example: I have an Image model linked to a Game model. Each Image has a category (the categories are fixed and number about 10). I want to get 3 images of each category (or less, if there aren't enough) for a game. This is the current implementation: from django.db import models class Game(models.Model): ... class Image(models.Model): category = models.CharField() image = models.ImageField() game = models.ForeignKey(Game) @classmethod def categories(cls): return ('category1', 'category2', ...) @classmethod def get_game_images(cls, game:Game): return [cls.objects.filter(game=game, category=category) for category in cls.categories()] # Do stuff with the images game = Game.objects.all().first() for category in Image.get_game_images(game): print(category) for image in category: print('\t', image.image.url) I feel a bit dumb doing 10 very similar queries to retrieve 3 elements each... A simple Image.objects.filter(game=game).order_by('category') gets close, but then ensuring there are only 3 rows per category becomes a bit complex. Is there a better way to accomplish the same result? Thank you -
How to add an AdminModel field to an existing ModelForm Django?
I am working on a CRM in Django. I have a Model Called "Query", and a ModelForm for it, called SimpleQueryForm, code below: class SimpleQueryForm(ModelForm): class Meta: model = Query fields = '__all__' Problem is, I have a field called "Customer" , which is a ForeignKey field. I don't want the form to have a dropdown, as it can get unpractical, so I tried to do the following, but it did not work: class SimpleQueryForm(ModelForm): class Meta: model = Query fields = '__all__' class QueryForm(admin.ModelAdmin): form = SimpleQueryForm fields = '__all__' #raw_id_fields = ("Customer",) autocomplete_fields = ['Customer'] QueryForm is supposedly the form used in my HTML template, as I am not using the Default Django Admin, I am making my own custom one. Any idea, how I can pull this off? How can I have an autocomplete field in my existing ModelForm? and is there a way by any chance to have a similar + button from admin, where you create a customer and it is automatically added to the ForeignKey of customers? I am genuinely new to all this, so please excuse my haste. -
Postgres doesn't respect Django's "on_delete = models.CASCADE" in models.py. Why?
I just migrated from SQLite3 to Postgres 12 (using pgloader). I can't delete certain model objects, because there are other model objects referencing to it. However, I'm very sure my model object has "on_delete = models.CASCADE" set in the referencing model object (in my Django code in models.py). So I get this error generated by Postgres: ... django.db.utils.IntegrityError: update or delete on table "app_reply" violates foreign key constraint "app_replyimage_reply_id_fkey" on table "app_replyimage" DETAIL: Key (id)=(SRB6Nf98) is still referenced from table "app_replyimage". Is there a way (hopefully without manually editing the table schema in Postgres) to resolve this? -
I tried to apply pagination to the search results, but the search condition was initialized the moment I pressed the page number
I have a one question I tried to apply pagination to the search results, but the search condition was initialized the moment I pressed the page number. after search by keyword this url is excuted http://127.0.0.1:8000/wm/myshortcut/go_to_skil_note_search_page_for_all/?q=test and after press pagi number this url is excuted http://127.0.0.1:8000/wm/myshortcut/go_to_skil_note_search_page_for_all/?page=2 url i want is this http://127.0.0.1:8000/wm/myshortcut/go_to_skil_note_search_page_for_all/?q=test&page=2 is this possible? Do I need to modify the view code to do this? Or do I need to edit the template? view is this class go_to_skil_note_search_page_for_all(LoginRequiredMixin,ListView): model = MyShortCut paginate_by = 10 def get_template_names(self): return ['wm/myshortcut_list_for_search2.html'] def get_queryset(self): if self.request.method == 'GET' and 'q' in self.request.GET: query = self.request.GET.get('q') else: query=" " print("query ::::::::::::::: ", query) print('seach user: {} search word: {} ################################################'.format(self.request.user, query)) qs = MyShortCut.objects.filter(Q(title__contains=query) | Q(filename__contains=query) | Q(content1__contains=query) | Q(content2__contains=query)).order_by('created') print("qs : ", qs) return qs template for pagi number: {% if is_paginated %} {% bootstrap_pagination page_obj size="small" justify_content="center" %} {% endif %} thanks for let me know ~! -
Django: proper way to get context data from another view
I have a menu that its content is obtained from a view, and that menu is in every view. Is there a proper way to get its context data to all my views without having to code again the same thing in every view? I was thinking returning that context on a JsonResponse of another view and parse it in every template with JavaScript like an API, but is it a good practice? -
i tried to load a img in django website but it is not loaded
<!Doctype html> <html> <head> <title>TEST</title> </head> <body> <h1 >Blog Home!</h1> {% load static %} <img src ="{% static 'images/imgtest.jpg' %}" /> </body> </html> </!Doctype html> this is the code Tree and the code in HTML please -
Selenium 'FirefoxWebElement' object has no attribute '_driver'
I'm using Selenium Webdriver (Firefox) with Python, I'm trying to press a log-in button: from selenium import webdriver from selenium.webdriver.common.keys import Keys actions = webdriver.ActionChains driver = webdriver.Firefox() driver.get('https://www.tiktok.com/foryou?lang=ru') login = driver.find_element_by_class_name('jsx-3665539393') actions.click(login) driver.close() It opens Firefox, goes to Tiktok website and then I get an error. Traceback (most recent call last): File "C:\Program Files\JetBrains\PyCharm 2020.1\plugins\python\helpers\pycharm\_jb_unittest_runner.py", line 35, in <module> sys.exit(main(argv=args, module=None, testRunner=unittestpy.TeamcityTestRunner, buffer=not JB_DISABLE_BUFFERING)) File "C:\Users\Danil\AppData\Local\Programs\Python\Python38-32\lib\unittest\main.py", line 100, in __init__ self.parseArgs(argv) File "C:\Users\Danil\AppData\Local\Programs\Python\Python38-32\lib\unittest\main.py", line 147, in parseArgs self.createTests() File "C:\Users\Danil\AppData\Local\Programs\Python\Python38-32\lib\unittest\main.py", line 158, in createTests self.test = self.testLoader.loadTestsFromNames(self.testNames, File "C:\Users\Danil\AppData\Local\Programs\Python\Python38-32\lib\unittest\loader.py", line 220, in loadTestsFromNames suites = [self.loadTestsFromName(name, module) for name in names] File "C:\Users\Danil\AppData\Local\Programs\Python\Python38-32\lib\unittest\loader.py", line 220, in <listcomp> suites = [self.loadTestsFromName(name, module) for name in names] File "C:\Users\Danil\AppData\Local\Programs\Python\Python38-32\lib\unittest\loader.py", line 154, in loadTestsFromName module = __import__(module_name) File "C:\Users\Danil\PycharmProjects\untitled4\work.py", line 9, in <module> actions.click(login) File "C:\Users\Danil\Desktop\MF\.venv\lib\site-packages\selenium\webdriver\common\action_chains.py", line 103, in click if self._driver.w3c: AttributeError: 'FirefoxWebElement' object has no attribute '_driver' Process finished with exit code 1 I'm Ok with program not pressing the button, because I'm learning, but why I get this error? -
I want to give users ten coins each time they create a post on my blog in django but it's not giving them automatically
I have tried alot of codes yet none of them have worked so I decided to leave the views unrelated to my models.py Here's my views.py below def journal_create_view(request): form = JournalModelForm(request.POST or None, request.FILES or None) if form.is_valid(): obj = form.save(commit=False) obj.user = request.user obj.Country = request.user.profile.your_country obj.slug = obj.Your_Post_Title obj.profile_pix = request.user.profile.image obj.save() return redirect('/journal/') form = JournalModelForm() template_name = 'add_post.html' context = {'form': form} return render(request, template_name, context) Here is my models.py user = models.OneToOneField(User,on_delete=models.CASCADE) name = models.CharField(max_length=50, blank=False,null=False) age = models.PositiveIntegerField(blank=False,null=False) phone = models.IntegerField(blank=False,null=False) your_country = models.CharField(max_length=50, blank=False) image = models.ImageField(blank=False,null=False, upload_to="profile_image") coins = models.IntegerField(default=100) def __str__(self): return self.user.username And lastly, here's my forms.py class Meta(): model = Profile fields = [ 'coins' ] I will be of gratitude if anyone help me out -
social-app-django Fehler 401: invalid_client The OAuth client was not found
Using social-app-django with google oauth2 is not working. It redirects me to google and then there is this message: Fehler bei der Autorisierung Fehler 401: invalid_client The OAuth client was not found. This is the url: https://accounts.google.com/signin/oauth/error?authError=Cg5pbnZhbGlkX2NsaWVudBIfVGhlIE9BdXRoIGNsaWVudCB3YXMgbm90IGZvdW5kLiCRAw%3D%3D&client_id=None Somehow the client_id is not added to the link. settings.py SOCIAL_AUTH_GOOGLE_KEY = '123456785439-123456789c7t6ektailibsmc4v5sc2ho.apps.googleusercontent.com' SOCIAL_AUTH_GOOGLE_SECRET = 'XXXXX_-XXXXXe_iAi2gJ3vv2' AUTHENTICATION_BACKENDS = ( 'social_core.backends.google.GoogleOAuth2', 'social_core.backends.github.GithubOAuth2', # working 'social_core.backends.twitter.TwitterOAuth', # working 'social_core.backends.facebook.FacebookOAuth2', # working 'django.contrib.auth.backends.ModelBackend', ) SOCIAL_AUTH_URL_NAMESPACE = 'social' urls.py urlpatterns = [ ... path('oauth/', include('social_django.urls', namespace='social')), ... ] I already completely recreated the project inside google developers console. It seems like somehow the client_id is not passed to the google login page, why? -
How to add a display name (username) with spaces in django?
I am creating an e-commerce website and I want the users to have usernames that allow spaces, but I came to know that this method will result in many issues, so I thought of two approaches to this The first approach is to create a new user model (It is still a new project, so it would not be a mess) and set the USERNAME_FIELD to the email(EmailField()) and then create a full_name field under that user model and set it to a CharField(),(But I am not sure f this if would allow spaces, if you tried it before please let me know). The second approach is creating a profile model, which will contain the user's image and also the display name, so the user will create his account and then he will be redirected to set his profile image and his display name(that accepts spaces). Before applying one of those two I want to know what would be the best for an e-commerce website. If there is any flaws in the method I mentioned please let me know, and if possible suggest a better logic for this. And If the display name will result in any issues please let … -
loging in a django site with python requests works for localhost (127.0.0.1:8000) and not on https://hosted-site.com
I have a django site which uses some auth views. I can successfully login to the site using python requests when I am running the site locally http://127.0.0.1:8000. However when I try to do the same on the the same site hosted on AWS ec2 instance I get a csrf token error. Below is the code and sample output! import requests #client = requests.session() email = "test" password = 'test_password' url_login = 'http://127.0.0.1:8000/users/login/' try: client.get(url_login) except requests.exceptions.RequestException as err: print("Lost connection again..", err) else: print('Connected') csrf_token = client.cookies['csrftoken'] login_data = {'username': email, 'password': password, 'csrfmiddlewaretoken': csrf_token} r1 = client.post(url_login, data=login_data) print(r1.text) print(r1.status_code) The output I get is: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <link href="https://fonts.googleapis.com/css?family=Crimson+Text:400,400i,600|Montserrat:200,300,400" rel="stylesheet"> <link rel="stylesheet" href="/static/landingpage/fonts/ionicons/css/ionicons.min.css"> <link rel="stylesheet" href="/static/landingpage/fonts/fontawesome/css/font-awesome.min.css"> <link rel="stylesheet" href="/static/landingpage/css/slick.css"> <link rel="stylesheet" href="/static/landingpage/css/slick-theme.css"> <link rel="stylesheet" href="/static/landingpage/css/helpers.css"> <link rel="stylesheet" href="/static/landingpage/css/style.css"> <link rel="stylesheet" href="/static/landingpage/css/landing-2.css"> <link rel="stylesheet" href="/static/landingpage/device-mockups/device-mockups.min.css"> <title>TIAT - The Teacher Interactive Assessment Tool</title> </head> <body data-spy="scroll" data-target="#pb-navbar" data-offset="200"> <section class="pb_xl_py_cover overflow-hidden pb_gradient_v1 cover-bg-opacity-8"> <div class="container"> <div class="row align-items-center justify-content-center"> <div class="col-md-5 justify-content-center"> <h2 class="heading mb-5 pb_font-40">Log in to your TIAT account!</h2> <div class="sub-heading"> <p class="mb-4">Check your accounts, back up data, collaborate … -
Convert UTC datetime fields to enduser's local datetime inside queryset in django
I have a custom filter which filters multiple date values(separated with comma) on datetime field. But before filter I should change UTC datetime values to user's local timezone values(not hardcoded). Here is my current code: models.py from device_model.api.models import DeviceModel from accessory_model.api.models import AccessoryModel from price_type.api.models import PriceType from project.api.models import Project class Price(models.Model): start_datetime = models.DateTimeField(blank=False, null=False,) end_datetime = models.DateTimeField(blank=True, null=True) price_type = models.ForeignKey(PriceType, models.DO_NOTHING, blank=False, null=False) sell_price = models.FloatField(blank=False, null=False) project = models.ForeignKey(Project, models.DO_NOTHING, blank=True, null=True) device_model = models.ForeignKey(DeviceModel, models.DO_NOTHING, blank=True, null=True) accessory_model = models.ForeignKey(AccessoryModel, models.DO_NOTHING, blank=True, null=True) is_second_hand = models.BooleanField(blank=True, null=False) class Meta: managed = False db_table = 'price' def save(self, *args,**kwargs): if not self.id: self.created_at=timezone.now() self.updated_at=timezone.now() return super(Price, self).save( *args,**kwargs) filters.py from price.api.models import Price from price.api.customfilter import DateListFilter class NumberInFilter(filter.BaseInFilter, filter.NumberFilter,): pass class CharInFilter(filter.BaseInFilter, filter.CharFilter): pass class PriceFilter(filter.FilterSet): id = NumberInFilter(field_name='id',lookup_expr='in') start_datetime = DateListFilter(field_name='start_datetime__date',lookup_expr='in') end_datetime = DateListFilter(field_name='end_datetime__date',lookup_expr='in') price_type = NumberInFilter(field_name='price_type',lookup_expr='in') sell_price = NumberInFilter(field_name='sell_price', lookup_expr='in') project = NumberInFilter(field_name='project',lookup_expr='in') device_model = NumberInFilter(field_name='device_model', lookup_expr='in') accessory_model = NumberInFilter(field_name='accessory_model', lookup_expr='in') is_second_hand = filter.BooleanFilter(field_name='is_second_hand') class Meta: model = Price fields = ['id','price_type','sell_price','project','device_model','accessory_model','is_second_hand', 'start_datetime','end_datetime'] customfilter.py class DateListFilter(filter.Filter): def filter(self,qs,value): if value not in (None,''): dates = [v for v in value.split(',')] # Before filter here should be change datetime from UTC to … -
Email send using app password - Username and Password not accepted?
I can't figure out why I can't send email in Django. I've enabled 2-step verification and generated App Password for this connection. But Gmail smtp returns: SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials q29sm16257362qtc.10 - gsmtp') I thought that using App Password will not cause such errors. EDIT: The email uses a custom domain but I guess this is not a problem. I haven't allowed less secured apps since I think it is not needed with App Password. -
Django Import-Export User Foreignkey & M2M Import Logic Check
Web Logic A user creates a new Trade object (enters data like Symbol, Broker, Notes, etc.) Trade is still empty The user creates entries now for this trade (ex. 100 shares @ $5 buy) Trade must have at least 2 Entires to be a closed trade Entries are added on the same form page as create trade using inlineformset_factory Model.py class Trade(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) status = models.CharField(max_length=2, choices=STATUS_CHOICES, default='cl') type = models.CharField(max_length=5, choices=TYPE_CHOICES, default=LONG) broker = models.ForeignKey(Broker, on_delete=models.CASCADE, blank=True, null=True) asset = models.ForeignKey(Asset, default=DEFAULT_ASSET_ID, on_delete=models.CASCADE, null=True) symbol = models.ForeignKey(Symbol, on_delete=models.CASCADE, blank=True, null=True) patterns = models.ManyToManyField(Pattern, blank=True) notes = RichTextUploadingField(blank=True, null=True) created = models.DateTimeField(editable=False) modified = models.DateTimeField(editable=False) associated_portfolios = models.ManyToManyField(Portfolio, blank=True) image = models.FileField(default='no-image-available-icon.jpg', upload_to=user_directory_path, null=True, blank=True) class Entry(models.Model): trade = models.ForeignKey(Trade, on_delete=models.CASCADE) date = models.DateTimeField(null=True, blank=True, default=datetime.datetime.now) amount = models.FloatField(null=True) price = models.FloatField(null=True) fee = models.FloatField(null=True, blank=True) entry_type = models.CharField(max_length=5, choices=ENTRY_TYPE_CHOICES, default=ENTRY) reg_fee = models.FloatField(null=True, blank=True) transaction_id = models.CharField(max_length=100, null=True, blank=True) Example CSV Data (I added space instead of "," to show data easier) Date/Time Description Amount Commission RegFee NetCashBalance 07/17/2020 7:42:39 Bought 40 APDN @ 14.56 -582.4 0 0 25,755.84 07/17/2020 7:47:16 Bought 40 APDN @ 14.78 -591.2 0 0 25,164.64 07/17/2020 7:53:36 Bought 20 APDN … -
Getting error when trying to insert JSON field in Postgres
I have the following schema in django. class function(models.Model): func_id = models.IntegerField(primary_key=True) func_name = models.CharField(max_length=30) func_args = JSONField() user = models.ForeignKey(user_data,on_delete=models.CASCADE) class Meta: db_table = 'function' When I am trying to run the following query INSERT INTO function(func_id,func_name,func_args,func_version,func_desc,user_id,container_path) VALUES (101,'Sum',{"input1":"a","input2":"b"},'1.7','blahblah',105,'/path'); I am getting below error: ERROR: syntax error at or near "{" LINE 1: ...nc_desc,user_id,container_path) VALUES (101,'Sum',{"input1":... Any clue where I am going wrong? -
Websockets to Heroku are giving a 404 on chrome/firefox
I have my Django application deployed on heroku. It uses websockets, and everything is configured properly. When I go to my site, the websockets fail with WebSocket connection to 'wss://<url>' failed: Error during WebSocket handshake: Unexpected response code: 404. I did some digging and it's apparently due to chrome blocking the websockets? I came across this issue which sounds like what I'm getting, but the answer did not fix it for me. Can someone explain what's going on here, and potentially how to fix it? -
formset and std. form won't save
I got two forms in one view, where one is a formset. When I hit submit, it does not save my data. What I try in my view is first to check the one, that is not the formset, and then check the formset. If both are valid, go ahead and save! My goal is that nothing will be saved if either of them has an error. I understand one is saving at this moment, without checking the formset. I got it like this for testing purposes. Where did I misunderstand something? view def new_invoice(request): invoice_form = NewInvoiceForm() formset = modelformset_factory(InvoiceItem, fields=('service', 'unit_price', 'quantity', 'vat_rule', 'unit')) items_form = formset() context = { 'invoice_form': invoice_form, 'items_form': items_form, 'invoice': Invoice, 'time': date } if request.method == 'POST': invoice_form = NewInvoiceForm(request.POST) if invoice_form.is_valid(): invoice_form_save = invoice_form.save() formset = formset(request.POST, instance=invoice_form_save) if formset.is_valid(): formset.save() return redirect('dashboard:dashboard') return render(request, 'dashboard/new-invoice.html', context) my form <form class="invoice-box" method="POST" action="." id="if"> {% csrf_token %} {% for forms in items_form %} <table cellpadding="0" cellspacing="0"> <tr class="top"> <td colspan="4"> <table> <tr class="heading"> <td colspan="3">Payment Method</td> <td>Check #</td> </tr> <tr class="details"> <td colspan="3">Check</td> <td>1000</td> </tr> <tr class="heading"> <td>Service</td> <td>Unit</td> <td>Quantity</td> <td>Price</td> <td>VAT Rate</td> <td>Total</td> </tr> <tr class="item"> <td> {% render_field forms.service … -
Django: custom dynamic search filter on admin filter_horizontal
I'm assuming that Django's built-in filter_horizontal widget allows search by the __str__() of the items (which is what is displayed in the filter_horizontal). Is it possible to make it also search other fields? For example, I have a model Shelf which has an m2m field to another model Parts. Parts has a brand field and a part number field. I want to be able to search and filter with filter_horizontal using both fields, but I only want to display the part number in the list on the filter_horizontal widget. I can't just make the __str__() return brand and part number because I use the model elsewhere. I would also prefer to use the filter_horizontal instead of an autocomplete field because it's more convenient when adding lots of Parts to a Shelf. -
Github oauth apache2 django daphne python-social-auth | Authentication failed ... redirect_uri
I can't get the oauth running on the productive server while there is no problem when testing with localhost:8000 during development. This is the setup: Apache as reverse proxy -> Daphne -> Django This is the exception as answer when clicking on the oauth button to login: AuthFailed at /oauth/complete/github/ Authentication failed: The redirect_uri MUST match the registered callback URL for this application. Request Method: GET Request URL: http://nomoney.shop/oauth/complete/github/?error=redirect_uri_mismatch&error_description=The+redirect_uri+MUST+match+the+registered+callback+URL+for+this+application.&error_uri=https%3A%2F%2Fdeveloper.github.com%2Fapps%2Fmanaging-oauth-apps%2Ftroubleshooting-authorization-request-errors%2F%23redirect-uri-mismatch&state=bHGqHRlbQjIYNKJWrb8t46ia1XV5OuxM Django Version: 3.0.5 Exception Type: AuthFailed Exception Value: Authentication failed: The redirect_uri MUST match the registered callback URL for this application. Apache Proxy settings: <VirtualHost *:443> ... ProxyPass / http://127.0.0.1:8002/ ProxyPassReverse / https://127.0.0.1:8002/ ProxyPreserveHost On ProxyRequests Off ... </VirtualHost> I think, the proxy setting causes that error but after hours of searching i cant find the solution. -
Django Stripe StripeDJ: Specify card for subsciption
I have a view for subscribing to a plan but I don't know how to specify which card to use or whether its a one time. Using the subscription serializer with all fields selected, only the plan_id field is provided. Post Method: def post(self, request, *args, **kwargs): try: serializer = self.serializer_class(data=request.data) if serializer.is_valid(): validated_data = serializer.validated_data stripe_plan = validated_data.get('stripe_plan', None) customer = self.get_customer() subscription = customer.subscribe(stripe_plan) return Response(subscription, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) except BaseException as e: error_data = {u'error': smart_str(e) or u'Unknown error'} return Response(error_data, status=status.HTTP_400_BAD_REQUEST) Serializer: class CurrentSubscriptionSerializer(ModelSerializer): class Meta: model = Subscription fields = '__all__'