Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Form, save to multiple tables
I'm working on an order entry system where it'll track products, recipes, and orders for customers. I'm trying to figure out how to create a recipe_ingredient form/template that will create a product entry, a recipe entry and an associated recipe ingredient entry(s) when the user creates a new recipe. The form should ask for the recipe name, description, along with the ingredients(products table), and percentage. Database Design (I don't know if I got the symbols correct) Here's my models.py for the product/recipe/recipe ingredient class Product(models.Model): name = models.CharField(max_length=200, null=True) sku = models.CharField(max_length=200, null=True, blank=True) supplier = models.ForeignKey(Supplier, null=True, on_delete= models.SET_NULL) description = models.CharField(max_length=200, null=True, blank=True) cost_per_pound = models.DecimalField(max_digits=7, decimal_places=2, blank=True) cost_per_ounce = models.DecimalField(max_digits=7, decimal_places=2, blank=True) note = models.CharField(max_length=1000, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) class Recipe(models.Model): name = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL) description = models.CharField(max_length=200, null=True, blank=True) class Recipe_Ingredient(models.Model): recipe_name = models.ForeignKey(Recipe, null=True, on_delete=models.SET_NULL) ingredient = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL) recipe_percent = models.DecimalField(max_digits=8, decimal_places=5, blank=True) I've got a semi-working recipe ingredient form, but the user will need to create the product first and then select it when creating the recipe and recipe ingredients. def recipeCreate(request): RecipeIngredientFormSet = forms.inlineformset_factory(Recipe, Recipe_Ingredient, form=RecipeIngredientForm, extra=10, fields=('ingredient', 'recipe_percent',)) form = RecipeForm() formset = RecipeIngredientFormSet() if request.method == … -
Hot to create cart endpoints with Django Rest framework?
im going to start develop an order functionality. Im building rest api's and i dont really understand what is right for a future SPA. Because i looked at examples on github and some people do endpoints for every action (add/delete/update/list) and some just for list and all decrement or increment quantity is on Vue side. So what should i do? How to do it right? I want it to be like every modern app, for example, delivery club or some. And by the way, do i need to use sessions in rest api? Because in Antonio Mele book he do e-shop but not rest framework and uses sessions with cart. -
How can I re-run a Django For Loop inside a HTML Div using Javascript on Click Event
I have a HTML div like this, <div class="coment-area "> <ul class="we-comet"> {% for j in comment %} <div id="delete_comment{{j.id}}" class="mt-3"> {% if j.post_id.id == i.id %} <li > <div class="comet-avatar"> {% if j.user_id.User_Image %} <img class="card-img-top" style=" vertical-align: middle;width: 50px;height: 50px;border-radius: 50%;" src= {{ j.user_id.User_Image.url }} alt=""> {% else %} <img class="card-img-top" style=" vertical-align: middle;width: 60px;height: 60px;border-radius: 50%;" src="static\images\resources\no-profile.jpg"> {% endif %} </div> Inside of it is a For Loop that is executed when the page is first loaded. Below this For Loop is a Comments Button <div > <button type="submit" onclick="comment_save(event,{{i.id}})" class= "my-2 ml-2 px-2 py-1 btn-info active hover:bg-gray-400 rounded ">Comment</button> </div> </div> </li> </ul> </div> Whenever this button of Comments is clicked, a function in Javascript is called which is defined below, function comment_save(event,post_id) { var comment_value=$("#comment_value"+post_id).val(); var user_id=$("#comment_user_id"+post_id).val() postdata={ "comment_value":comment_value, "user_id":user_id, "post_id":post_id } SendDataToServer("readmore",postdata,function() { alert() }) $("#comment_value"+post_id).val(" ") <! --- document.location.reload().. Something here that refresh that for loop ---> } What I want is this that whenever the button is clicked, it re-executes that for Loop inside my main div without having to refresh the page. I have been trying to do this for two days but could not find any solution to this. Can … -
How can I define a check constraint on a string length (Django)
I am looking to do the following: constraints = [models.CheckConstraint(check=Length('code')==5, name='code_length')] It fails because the check argument needs to be a A Q object or boolean Expression that specifies the check you want the constraint to enforce I'm not seeing string length field lookup nor am I seeing a way to incorporate the Length database function into a Q object argument. The only other option is a boolean expression (which is what I aimed at in my failed attempt above) but apparently this is an API that I have to implement. I am new to Django and would appreciate the help. -
Django Filter Returning Attribute Errors
I have the following code, that is purposed to create a filtered view of my dataset based on a few dropdown selections defined in MyFilter. In my /picks url, I see the search bar but no criteria to filter with. When I navigate to /picks/8 to test the filtering, I get the following attribute with my model. I've also tried orders = Pick.order_set.all() with no luck as well. Any suggestions on how to get this working? error: 'Pick' object has no attribute 'order_set' pick_list.html: <form method="get"> {{myFilter.form}} <button class="btn btn-primary" type="submit">Search</button> </form> views.py def week(request, pk_test): week = Pick.objects.get(id=pk_test) orders = week.order_set.all() myFilter = PickFilter(request.GET, queryset=orders) orders = myFilter.qs context = {'week':week, 'orders':orders, 'order_count':order_count, 'myFilter':myFilter} return render(request, 'app/pick_list.html',context) filters.py class PickFilter(django_filters.FilterSet): age = CharFilter(field_name='name', lookup_expr='icontains') name = CharFilter(field_name='name', lookup_expr='icontains') class Meta: model = Pick fields = '__all__' exclude = ['photo'] models.py class Pick(models.Model): submitter = models.CharField(max_length=50, verbose_name='Submitter', null=True, blank=True) week = models.CharField(max_length=50, verbose_name='Week', null=True, blank=True) name = models.CharField(max_length=50, verbose_name='Name', null=True, blank=True) photo = models.CharField(max_length=50, verbose_name='Photo', null=True, blank=True) #photo = models.ImageField(upload_to="media", max_length=500, verbose_name='Photo', null=True, blank=True) hometown = models.CharField(max_length=50, verbose_name='Hometown', null=True, blank=True) age = models.IntegerField(verbose_name='Age', null=True, blank=True) progress = models.IntegerField(verbose_name='Progress', null=True, blank=True) occupation = models.CharField(max_length=50, verbose_name='Occupation', null=True, blank=True) elim_week = models.CharField(max_length=50, verbose_name='Week … -
Get values from another table python
I would like to get column named 'work_id' from table Duties. The common column in table User and Duties is account_id(for User) and ID(for Duties), this is the same value. The Duties is pk in model User. Right now I have function, that sending csv file to email with id, name and account_id column from table User. def send_csv(): data = {} person_data= User.objects.values('uid', 'state', 'account_id') buffer = io.StringIO() writer = csv.writer(buffer) for person_data in User.objects.filter(state=User.Active): writer.writerow([person_data.uid, person_data.account_id) buffer = io.StringIO() writer = csv.writer(buffer) for person_data in User.objects.filter(state=User.Disabled): writer.writerow([person_data.uid, person_data.account_id) email = EmailMessage('CSV statistic', to=settings.MAIL) email.attach('active.csv', buffer.getvalue(), 'text/csv') email.attach('disabled.csv', buffer2.getvalue(), 'text/csv') email.send() Please help me with this, a little bit stuck. I would like also send column work_id with correct uid and account_id from table User Tables example: User uid name last_name state account_id 1ldwd John Black active 123 2fcsc Drake Bell disabled 456 3gscsc Pep Guardiola active 789 4vdded Steve Salt disabled 012 Table Duties uid rate hobbie account_id work_id 1sdeed part football 456 007 3rdfd full hockey 789 022 45ffdf full regbie 123 4567 455ggg part fishing 012 332 -
With django, how to control the server's stop and start again by batch.bat via a button on the screen, use the Windows operating system
With django, how to control the server's stop and start again by batch.bat via a button on the screen, use the Windows operating system all the methods I got The process is done manually and I didn't find an automated way or code that works on it for example: 1-I have to Open Windows PowerShell as Administrator Find PID (ProcessID) for port 8080: netstat -aon | findstr 8000 TCP 0.0.0.0:8080 0.0.0.0:0 LISTEN 77777 Kill the zombie process: taskkill /f /pid 77777 Now we return to the question how can I do this process automatically, either through the batch.bat file or through the django code -
Internal Server Error: AssertionError: Expected a `Response`, `HttpResponse` to be returned from the view, but received a `<class 'NoneType'>`
code The above image has the code and below one is the erorr which I am getting, if i am using post man to test my API seperatly it's working prorperly. AssertionError: Expected a Response, HttpResponse or HttpStreamingResponse to be returned from the view, but received a <class 'NoneType'> -
pika.exceptions.AMQPConnectionError in Django with Docker
I'm using docker to run two django services. RabbitMq is installed in the host not in a container. When I run the django development server without the container rabbitmq connection works. But when I use the docker-compose up it gives pika.exceptions.AMQPConnectionError error. I restarted the rabbitmq but it doesn't resolve the problem Dockerfile FROM python:3.9 ENV PYTHONUNBUFFERED 1 WORKDIR /app COPY requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app CMD python manage.py runserver 0.0.0.0:8000 Dockercompose.yml version: '3.3' services: blog_writer: build: context: . dockerfile: DockerFile ports: - 8001:8000 volumes: - .:/app Producer.py import json import pika connection = pika.BlockingConnection(pika.ConnectionParameters('localhost', heartbeat=600, blocked_connection_timeout=300)) channel = connection.channel() def publish(method, body): properties = pika.BasicProperties(method) channel.basic_publish(exchange='', routing_key='blogs', body=json.dumps(body), properties=properties) RabbitMq Status sudo systemctl status rabbitmq-server.service [sudo] password for navanjane: ● rabbitmq-server.service - RabbitMQ broker Loaded: loaded (/lib/systemd/system/rabbitmq-server.service; enabled; vend> Active: active (running) since Sat 2022-01-15 18:51:40 +0530; 1 day 5h ago Main PID: 1105 (beam.smp) Tasks: 28 (limit: 9342) Memory: 105.7M CGroup: /system.slice/rabbitmq-server.service ├─1105 /usr/lib/erlang/erts-12.1.5/bin/beam.smp -W w -MBas ageffcb> ├─1170 erl_child_setup 32768 ├─1556 /usr/lib/erlang/erts-12.1.5/bin/epmd -daemon ├─1588 inet_gethost 4 └─1589 inet_gethost 4 ජන 15 18:51:35 navanjane-Ubuntu rabbitmq-server[1105]: Doc guides: https://r> ජන 15 18:51:35 navanjane-Ubuntu rabbitmq-server[1105]: Support: https://r> ජන 15 18:51:35 navanjane-Ubuntu rabbitmq-server[1105]: Tutorials: https://r> ජන … -
Cannot assign "2": "OrderProduct.product" must be a "Product" instance
**Hi everyone I want to move the Cart Items to Order Product Table after payment First, the products are get from the card item model. Product number is multiplied by product price ,and I got the order model for got the order total My Cart item were not moved to Order Product table How Can I move them? I got this error ValueError at /go-to-gatewey/** enter image description here ValueError at /go-to-gatewey/ Cannot assign "2": "OrderProduct.product" must be a "Product" instance. Request Method: GET Request URL: http://127.0.0.1:8000/go-to-gatewey/ Django Version: 3.2.9 Exception Type: ValueError Exception Value: Cannot assign "2": "OrderProduct.product" must be a "Product" instance. Exception Location: E:\English Projects_I Do it\Second_Project\GreatKart_Persian\venv\lib\site-packages\django\db\models\fields\related_descriptors.py, line 215, in set Python Executable: E:\English Projects_I Do it\Second_Project\GreatKart_Persian\venv\Scripts\python.exe payment function: def go_to_gateway_view(request,total=0, quantity=0): cart_items = CartItem.objects.filter(user=request.user) for cart_item in cart_items: total += (cart_item.product.price * cart_item.quantity) quantity += cart_item.quantity tax = (2 * total) / 100 grand_total = total + tax form = OrderForm(request.POST) data = Order() data.order_total = grand_total data.tax = tax # Generate order number yr = int(datetime.date.today().strftime('%Y')) dt = int(datetime.date.today().strftime('%d')) mt = int(datetime.date.today().strftime('%m')) d = datetime.date(yr, mt, dt) current_date = d.strftime("%Y%m%d") # Like this : 2021 03 05 order_number = current_date + str(data.id) data.order_number = order_number … -
Django - TypeError __init__() missing 1 required positional argument when uploading a file
I want to set an initial value "test" to the field name when I'm uploading a file with a Django. Here is what I tried in views.py: class UploadFile(CreateView): form_class = UploadFileForm template_name = "tool/upload.html" success_url = reverse_lazy('tool:index') fields = ['file',] def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST, request.FILES) if form.is_valid(): form.save() return redirect(self.success_url) else: return render(request, self.template_name, {'form': form}) And in forms.py: class UploadFileForm(forms.ModelForm): class Meta: model = CheckFile fields = ['file', ] def __init__(self, file, *args, **kwargs): file = kwargs.pop('file') super(UploadFileForm, self).__init__(*args, **kwargs) if file: self.fields['name'] = "test" But I end up having the following error: TypeError: UploadFileForm.__init__() missing 1 required positional argument: 'file' I don't understand why I keep having this error. Could you please help me? Thanks! -
How do I register and log-in a User in django-rest-framework?
I have no idea how to do it. I just want to know the best way to register and/or log-in a User through rest API. I would be thankful for any code snippets or documentatnion links. -
trying to deploy django to heroku - error message
I tried to deploy my django to heroku and i get this error. -----> Building on the Heroku-20 stack -----> Determining which buildpack to use for this app ! No default language could be detected for this app. HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. See https://devcenter.heroku.com/articles/buildpacks ! Push failed please help... -
ElasticSearch tutorial: Getting ValueError from bulk_indexing
I am following this tutorial. https://medium.com/free-code-camp/elasticsearch-with-django-the-easy-way-909375bc16cb#.le6690uzj Tutorial is about using elasticsearch with django app. I am stuck when it ask to use bulk_indexing() in shell. I am getting this error ** raise ValueError("You cannot perform API calls on the default index.") ValueError: You cannot perform API calls on the default index.** >>>python manage.py shell Python 3.10.0 | packaged by conda-forge | (default, Nov 10 2021, 13:20:59) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from elasticApp.search import * >>> bulkIndexing() Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Users\jatin.kumar.in\Documents\JK\Project\elasticApp\search.py", line 17, in bulkIndexing ArticleIndex.init() File "C:\Users\jatin.kumar.in\Miniconda3\envs\Project\lib\site-packages\elasticsearch_dsl\document.py", line 156, in init i.save(using=using) File "C:\Users\jatin.kumar.in\Miniconda3\envs\Project\lib\site-packages\elasticsearch_dsl\index.py", line 298, in save if not self.exists(using=using): File "C:\Users\jatin.kumar.in\Miniconda3\envs\Project\lib\site-packages\elasticsearch_dsl\index.py", line 414, in exists return self._get_connection(using).indices.exists(index=self._name, **kwargs) File "C:\Users\jatin.kumar.in\Miniconda3\envs\Project\lib\site-packages\elasticsearch_dsl\index.py", line 134, in _get_connection raise ValueError("You cannot perform API calls on the default index.") ValueError: You cannot perform API calls on the default index. >>> Help me in solving this error. -
Django models adding member to a project
Trying to figure out how to create a Project class for an app I am making. I am bringing inn a Profile from another app, containing username, names and avatar. Then i need a project name and i want to be able to bring inn members, to the specific project, but don't know how to go forward with that. models.py from django.db.models.deletion import CASCADE from django.db import models from profiles.models import Profile class Projects(models.Model): user = models.ForeignKey(Profile, on_delete=CASCADE) project_name = models.CharField(max_length=55, null=True, blank=True) members = how to get members inn this? Will add tasks, notes and a chat as seperate classes then bring them inn to the project as foreignkey, think that would be correct. But how to deal with the members and get them added to the project? -
Not Found The requested resource was not found on this server
I follow this address and I set DEBUG = False in appartement/settings.py in my project. I changed /etc/apache2/sites-available/000-default.conf: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /media /var/www/b9/appartement/cdn/cdn_medias Alias /static /var/www/b9/appartement/cdn/cdn_assets <Directory /var/www/b9/appartement/cdn/cdn_medias/> Require all granted </Directory> <Directory /var/www/b9/appartement/cdn/cdn_assets/> Require all granted </Directory> <Directory /var/www/b9/appartement/appartement> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess appartement python-path=/var/www/b9/appartement:/var/www/b9/django-virtualenv_b9/lib/python3.8/site-packages WSGIProcessGroup appartement WSGIScriptAlias /appartement /var/www/b9/appartement/appartement/wsgi.py </VirtualHost> but when i run django project, i got Not Found error about statics files and it can not found CSS files -
If any are null, do something
I have a view that performs some basic calculations, but sometimes not all fields have values added, so the calculations fail due to trying to do calculations that do exist. Is there a way to say if any fields contain null or blank then pass or do i need to write a if for every one? if QuestionnaireResponse.objects.filter(project_name_id=project_id, questionnaire_id=1).exists(): dist_resp = QuestionnaireResponse.objects.get(project_name_id=project_id, questionnaire_id=1) artist_percent = QuestionnaireAnswer.objects.get(question_id=3,response=dist_resp) marketing_percent = QuestionnaireAnswer.objects.get(question_id=4,response=dist_resp) advisers_percent = QuestionnaireAnswer.objects.get(question_id=5,response=dist_resp) community_percent = QuestionnaireAnswer.objects.get(question_id=6,response=dist_resp) team_percent = QuestionnaireAnswer.objects.get(question_id=7,response=dist_resp) partners_percent = QuestionnaireAnswer.objects.get(question_id=8,response=dist_resp) reserve_percent = QuestionnaireAnswer.objects.get(question_id=9,response=dist_resp) artist_percent_allocation = ((project.project_total_supply / 100)*(artist_percent.answer)) marketing_percent_allocation = ((project.project_total_supply / 100)*(marketing_percent.answer)) advisers_percent_allocation = ((project.project_total_supply / 100)*(advisers_percent.answer)) community_percent_allocation = ((project.project_total_supply / 100)*(community_percent.answer)) team_percent_allocation = ((project.project_total_supply / 100)*(team_percent.answer)) partners_percent_allocation = ((project.project_total_supply / 100)*(partners_percent.answer)) reserve_percent_allocation = ((project.project_total_supply / 100)*(reserve_percent.answer)) I have set a if on the first line which works, but sometimes that if can return true, but the lines below could be null. marketing_percent_allocation = ((project.project_total_supply / 100)*(marketing_percent.answer)) advisers_percent_allocation = ((project.project_total_supply / 100)*(advisers_percent.answer)) community_percent_allocation = ((project.project_total_supply / 100)*(community_percent.answer)) team_percent_allocation = ((project.project_total_supply / 100)*(team_percent.answer)) partners_percent_allocation = ((project.project_total_supply / 100)*(partners_percent.answer)) reserve_percent_allocation = ((project.project_total_supply / 100)*(reserve_percent.answer))` Is this possible? Thanks -
Can't connect MPTT with django.parler
I do e-commerce in django. I have Category model that I want to work with both django.parler and django-MPTT, because I want to make subcategories for category. I've done everything like in django-parler documentation to connect these two packages the right way. After saving the model, the following error appears: ImproperlyConfigured at /pl/admin/store/category/ TreeQuerySet class does not inherit from TranslatableQuerySet And I'm not sure why. My Category model: models.py class Category(MPTTModel, TranslatableModel): parent = TreeForeignKey('self', related_name='children', on_delete=models.CASCADE, blank=True, null=True) slug = models.SlugField(max_length=200, db_index=True, unique=True, blank=True, null=True, default='') translations = TranslatedFields( name=models.CharField(max_length=200, db_index=True, blank=True, null=True, default=''), ) class Meta: unique_together = ['slug', 'parent'] verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): full_path = [self.name] k = self.parent while k is not None: full_path.append(k.name) k = k.parent return ' -> '.join(full_path[::-1]) def get_absolute_url(self): return reverse('store:product_list_by_category', args=[self.slug]) admin.py @admin.register(Category) class CategoryAdmin(TranslatableAdmin, MPTTModelAdmin): list_display = ['name', 'slug', 'parent'] search_fields = ['name'] def get_populated_fields(self, request, obj=None): return {'slug': ('name',)} -
ForigenKey in django preselected when creating a modelform for a a relation table
I want to have the Forgienkey to be preselected of it's relation table id, in example i want to create a job for a specific component with the component being already chosen. my view.py : def create_job(request, pk): component = Component.objects.all() component_id = Component.objects.get(id=pk) obj = Job.objects.get() obj.component_id(id=pk) instance = JobModelForm(instance=obj) form = JobModelForm() if request.method == 'POST': form = JobModelForm(request.POST,) if form.is_valid(): form.save() return HttpResponseRedirect(request.path_info) context = { 'components': component, 'component_id': component_id, "form": form, "instance":instance, } return render(request, 'create_job.html', context) the form template : <form method='POST' action=''> {% csrf_token %} <span class="component-label-text">Job name</span> {% render_field form.name class="component-form-data-inputs" %} <span class="component-label-text">Job description</span> {% render_field form.description class="component-form-data-inputs" %} <span class="component-label-text">Job type</span> {% render_field form.type class="component-form-data-inputs" %} <span class="component-label-text">Check if Job is critical</span> {% render_field form.is_critical %} <br> <span class="component-label-text">Job interval</span> {% render_field form.interval class="component-form-data-inputs" %} <span class="component-label-text">Job Due date</span> {% render_field form.due_date %} <br> {% render_field instance.component class="component-form-data-inputs" %} <input type="submit" class="button1" value='Create Job' /> </form> -
Django Allauth: Duplicate Key Value Violates Unique Constraint: Key (username)=() already exists
I have been troubleshooting an issue with my custom allauth Django user model for some time. I only want to use email, first name, last name, and password as part of my user signup form, and I can get it to work once, but when a second user signs up, it says that the username already exists. I have seen others with a similar issue, but unfortunately their solutions do not work. If I remove the custom account form, then it does, but I need to include first name and last name in my signup form, so not sure how to work around that. Any help is appreciated! settings.py AUTH_USER_MODEL = 'accounts.CustomUser' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_USER_MODEL_USERNAME_FIELD = None # I have also tried ACCOUNT_USER_MODEL_USERNAME_FIELD = 'username' and 'email' ACCOUNT_FORMS = { 'signup': 'accounts.forms.CustomUserCreationForm' } models.py class CustomUser(AbstractUser): email = models.EmailField(max_length=256) first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) REQUIRED_FIELDS = ['email', 'first_name', 'last_name'] forms.py class CustomUserCreationForm(UserCreationForm): class Meta: model = get_user_model() fields = ('email', 'first_name', 'last_name') -
How to get instance from global id in Django with Graphene Relay
graphql_relay has a function from_global_id which returns the model_name and the instance_id. However, it seems that to retrieve the model from the name of the model, we need to know in which app the model is, such as answers in the question asking how to get the model from its name. Is there a way to know the name of the app from the global id? Or is there any other way to retrieve the instance? -
Django and stripe handle successful payment
I am trying to handle successful payment using stripe webhook, in my stripe dashboard I see that the events are triggered and the payment_intent is successful but the order is not created views.py : from django.shortcuts import render from django.http import JsonResponse from django.http import HttpResponse import stripe import json from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.views.decorators.http import require_POST from article.models import Order endpoint_secret = '1wwww' @require_POST @csrf_exempt def my_webhook_view(request): payload = request.body sig_header = request.META['HTTP_STRIPE_SIGNATURE'] event = None # Try to validate and create a local instance of the event try: event = stripe.Webhook.construct_event(payload, sig_header, endpoint_secret) except ValueError as e: # Invalid payload return HttpResponse(status=400) except stripe.error.SignatureVerificationError as e: # Invalid signature return HttpResponse(status=400) # Handle the checkout.session.completed event if event['type'] == 'payment_intent.succeeded': checkout_session = event['data']['object'] # Make sure is already paid and not delayed _handle_successful_payment(checkout_session) # Passed signature verification return HttpResponse(status=200) def _handle_successful_payment(checkout_session): payed_order = Order.objects.create(order_id='test22') return payed_order -
Django - Could not parse the remainder: '++_RS' from 'annovar.GERP++_RS'
I have a JSON value that comes directly from a DB that has this label GERP++_RS This is part of a big dictionary and I need to display the correspondent value on a HTML page, but Django gives me this error Could not parse the remainder: '++_RS' from 'annovar.GERP++_RS' What would be best strategy to retrieve the value from this key? Would I need to process it before it gets to the template? Thanks in advance -
how to run django in pycharm in https
I need to run a python Django project with Pycharm IDE locally in HTTPS so that other services can talk with my service without any errors. I don't manage to run it locally in HTTPS -
Passing and using the request object in django forms
I'm trying to user the request object to create a dynamic dropdown list in my form using the following code: view: form = TransactionForm(request.user) form: class TransactionForm(forms.Form, request.user): # Payment methods get_mm_details = MMDetails.objects.filter(username=request.user) get_card_details = CardDetails.objects.filter(username=request.user) payment_meth = [] # form fields trans_amount = forms.IntegerField(label="Amount", min_value=0) payment_method = forms.CharField( label='Payment method', widget=forms.Select( choices=payment_meth ) ) is there a way of using the request object in a form?