Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Update an existing field when another object of same name is added to the table
I'm fairly new to Django, hence open for any kind of suggestions I have two models Order and Stock My code: models.py class Order(models.Model): idorder = models.AutoField(db_column='idorder', primary_key=True) date_ordered = models.DateField(db_column='Date_Ordered', blank=True, null=True) # Field name made lowercase. number_ordered = models.IntegerField(db_column='Number_Ordered', blank=True, null=True) # Field name made lowercase. idproduct = models.ForeignKey(Product, models.DO_NOTHING, blank=True, db_column='idProduct', verbose_name='Product Name') # Field name made lowercase. idsupplier = models.ForeignKey(Supplier, models.DO_NOTHING, blank=True, db_column='idSupplier', verbose_name='Supplier Name') # Field name made lowercase. class Meta: managed = False db_table = 'order' class Stock(models.Model): idstock = models.AutoField(primary_key=True) quantity = models.IntegerField(db_column='Quantity', blank=True, null=True) # Field name made lowercase. idproduct = models.ForeignKey(Product, models.DO_NOTHING, db_column='idProduct', verbose_name='Product Name', blank=True) # Field name made lowercase. idorder = models.ForeignKey(Order, models.DO_NOTHING, db_column='idOrder', verbose_name='Order Name', blank=True) class Meta: managed = False db_table = 'stock' def __str__(self): #to return supplier_name for foreign key references return self.idproduct.product_name I have implemented the addition of corresponding Order object into Stock table using signals #this signal is to add object to stock automatically when order object is created def create_stock_item(sender, instance, created, **kwargs): if created: s = Stock( idorder=instance, quantity=instance.number_ordered, idproduct=instance.idproduct ) s.save() post_save.connect(create_stock_item, sender=Order) When I add an Order, the corresponding Stock object is created What I want to achieve is that … -
Django Celery consuming from AWS SQS
I have a Django app running celery already connected to SQS, everything works if I send the tasks thought Django. But I want to try to send tasks from Cloudflare Workers which use JS. This is the code I'm running in Cloudflare: const client = new SQSClient({ region: "eu-west-3", credentialDefaultProvider: myCredentialProvider }); const send = new SendMessageCommand({ // use wrangler secrets to provide this global variable QueueUrl: URL_HERE, MessageBody: { 'lang': 'py', 'task': 'config.celery.debug_task', 'id': taskId, 'shadow': null, 'eta': null, 'expires': null, 'group': null, 'retries': 0, 'timelimit': [null, null], 'root_id': taskId, 'parent_id': null, 'argsrepr': "", 'kwargsrepr': '{}', 'origin': 'gen46150@Marcoss-MacBook-Pro.local', 'reply_to': uuidv4(), 'correlation_id': taskId, 'hostname': 'celery@Marcoss-MacBook-Pro.local', 'delivery_info': { 'exchange': '', 'routing_key': 'default', 'priority': 0, 'redelivered': null }, 'args': [{ 'hello': 'wolrd', 'success': true }], 'kwargs': {}, 'is_eager': false, 'callbacks': null, 'errbacks': null, 'chain': null, 'chord': null, 'called_directly': false, '_protected': 1 } }); The message gets to SQS correctly and my Django app tries to execute. But I get this error: File "/usr/local/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/__init__.py", line 357, in loads return _default_decoder.decode(s) File "/usr/local/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/local/opt/python@3.8/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char … -
Select dropdown from another model is not working in django-import-export
I am trying to implement django-import-export in an existing django app. When I'm trying to select an item from dropdown (ForeignKey), I can select the item but it does not save in the subject data. Please see the screenshot for more details: Import Screen: Confirm Screen: [subject is not selected] Here is my code: models.py file class Subject(models.Model): subject = models.CharField( max_length=250, blank=True, null=True) def __str__(self): return self.subject class Answer(models.Model): question = models.ForeignKey(MCQQuestion, verbose_name='Question', on_delete=models.CASCADE) subject = models.ForeignKey(Subject, on_delete=models.CASCADE, blank=True, null=True) content = models.CharField(max_length=1000, blank=False, help_text="Enter the answer text that \ you want displayed", verbose_name="Content") correct = models.BooleanField(blank=False, default=False, help_text="Is this a correct answer?", verbose_name="Correct") def __str__(self): return self.content class Meta: verbose_name = "Answer" verbose_name_plural = "Answers" forms.py file from django import forms from import_export.forms import ImportForm from .models import Subject class CustomImportForm(ImportForm): subject = forms.ModelChoiceField( queryset=Subject.objects.all(), required=True) admin.py file from django.contrib import admin from import_export import resources from import_export.admin import ImportExportModelAdmin from import_export import fields, resources from .forms import CustomImportForm from .models import Answer, Subject class AnswerResource(resources.ModelResource): class Meta: model = Answer chunk_size = None fields = ['id', 'question', 'content', 'correct', 'subject'] class AnswerAdmin(ImportExportModelAdmin): resource_class = AnswerResource def get_import_form(self): return CustomImportForm def get_form_kwargs(self, form, *args, **kwargs): # pass on … -
How to serialize only certain elements of M2M set of the object being serialized?
So I have these models: class Group(models.Model): name = models.CharField(max_length=255, blank=True, null=True, default=None) class Member(models.Model): name = models.CharField(max_length=255, blank=True, null=True, default=None) group = models.ForeignKey(Group, related_name='members', on_delete=models.CASCADE) is_deleted = models.BooleanField() And these serializers: class GroupSerializer(serializers.ModelSerializer): members = MemberSerializer(many=True, read_only=True) class Meta: model = Group fields = '__all__' class MemberSerializer(serializers.ModelSerializer): # some field defintions here class Meta: model = Member fields = '__all__' And view: class GroupViewSet(viewsets.ModelViewSet): queryset = Group.objects.all() serializer_class = GroupSerializer Now what I want to do basically, is not return "members" of Group that has is_deleted set to True. So if I have a Group with 3 Member where 1 has is_deleted set to True, I want my serializer to return the Group with 2 Members. How do I go about achieving this? -
How do I convert 2021-01-05T23:19:30.685658Z to dd-mm-yyyy
In my django app I am getting the date returned in the following format 2021-01-05T23:19:30.685658Z How do I convert this to dd-mm-yyyy? -
getting NameError when tries to migrate mySQL database into django project
I have a django - mySQL migration problem. I can not figure out what is the problem, please if you have any idea let me know. I try to change the basic sqlite3 database to mySQL. I started a new django project. I work on mac, I use virtual env and my python version 3.9.0. I have installed pip and homebrew. I installed mysql with homebrew. I made a sample database in mysql, and also checked in the workbench. I started mysql. I installed mysqlclient (2.0.3) via pip. I opened my project and change the DATABASE = {...} in settings.py to: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'sample', 'HOST': '127.0.0.1', 'PORT': '3306', 'USER': 'root', 'PASSWORD': 'thisisreallymypassword', } } My problem is when I run the python manage.py -migrate command I always get NameError: name '_mysql' is not defined. I went through all the topics, but can't figure out the problem. Any idea? (env) Csutkas-MacBookPro:greenium gezamacbookpro$ pip freeze asgiref==3.3.1 Django==3.1.4 django-filter==2.4.0 django-mysql==3.10.0 mysqlclient==2.0.3 Pillow==8.0.1 pytz==2020.4 sqlparse==0.4.1 (env) Csutkas-MacBookPro:greenium gezamacbookpro$ python manage.py migrate Traceback (most recent call last): File "/Users/gezamacbookpro/env/lib/python3.9/site-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: dlopen(/Users/gezamacbookpro/env/lib/python3.9/site-packages/MySQLdb/_mysql.cpython-39-darwin.so, 2): Library not loaded: @rpath/libmysqlclient.21.dylib Referenced from: /Users/gezamacbookpro/env/lib/python3.9/site-packages/MySQLdb/_mysql.cpython-39-darwin.so Reason: image … -
Why i cannot give this values
I want to when i click on the user discharge button it will go to the page and the all user information take automatically. But i cannot get this value. Here is the image in the discharge button i click but its shows like this. Here is my code : views.py def discharge_view(request, pk): form = DischargForm() if request.method == 'POST': form = DischargForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Successfull') return redirect('discharge-patient') context = { 'form': form, } return render(request, 'hospital/discharge.html', context) forms.py : class DischargForm(forms.ModelForm): class Meta: model = PatientDischarge fields = ('assign_doctor', 'admitted', 'release_date', 'medicine_cost', 'other_charge') widgets = { 'assign_doctor': forms.Select(attrs={'class': 'form-control'}), 'admitted': forms.Select(attrs={'class': 'form-control'}), 'release_date': forms.TextInput(attrs={'class': 'form-control'}), 'medicine_cost': forms.TextInput(attrs={'class': 'form-control'}), 'other_charge': forms.TextInput(attrs={'class': 'form-control'}), } discharge.html {% extends 'base.html' %} {% block content %} Discharge patient {% csrf_token %} {% for fields in form %} {{ fields.label_tag }} {{ fields }} {% endfor %} {% endblock %} -
Django grouped queryset with subqueries
I'm trying to create a grouped queryset in Django to first group by occupation and then aggregate sum of occupation by date_rented where date_rented is grouped by month. I have been able to accomplish getting the desired results in python but it seems rather inefficient to me as it is necessary to do subqueries for each occupation to get the sum according to date_rented. Failing being able to use Django's built-in query API, I suppose I will have no choice but to use this solution, but if anyone can help me solve this using Django built in query API, I will be eternally grateful. Model class Tenant(models.Model): name = models.CharField(max_lenght=254) occupation = models.CharField(max_length=254) date_rented = models.DateField() Sample Data | id | name | occupation | date_rented | | -- | ----------------- | ------------------ | ------------- | | 1 | Orlando Barrero | Electrician | 2020-01-13 | | 2 | Miguel Espinosa | Mechanic | 2020-01-24 | | 3 | Renan Figueroa | Electrician | 2020-02-22 | | 4 | Marco Galvez | Mechanic | 2020-03-13 | | 5 | Eric Mendosa | Mechanic | 2020-03-22 | | 6 | Giovani Vela | Electrician | 2020-03-24 | Expected Result | occupation … -
how to get instance of a model form and assign it to its key in view?
During form processing, I'd like to be able to set a foreign key field on a model object from its base model when the user selects a value from the dropdown list. models.py class Question(models.Model): question = models.CharField(max_length=200) class Teacher(models.Model): name = models.CharField(max_length=200) l_name = models.CharField(max_length=200) class Student_Answer(models.Model): teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.SmallIntegerField(choices=RATING_CHOICES) For example, I have five records in model A, two records in model B and I have two model forms. forms.py class AnswerForm(ModelForm): class Meta: model = Student_Answer fields = ('answer',) widgets = { 'answer': RadioSelect(choices=RATING_CHOICES),} class TeacherForm(ModelForm): name = ModelChoiceField(queryset=Teacher.objects.all()) class Meta: model = Teacher fields = ('name',) For the questions, I just assign them directly within the view and then giving the instances to the foreign key after validation. Now, if I do the same for Teacher I mean this teacher = Teacher.objects.get(id=2) and then choice.teacher = teacher it's going to work perfectly. But that is not the case which I want. The teacher will be selected by the user. I am looking for a way like the below view. views.py def index(request): question1 = Question.objects.get(id=6) question2 = Question.objects.get(id=7) if request.method == "POST": teacher_form = TeacherForm(request.POST) form = AnswerForm(request.POST, … -
DJANGO - Reduce amount of field in queryset
I have a model Product with a lot of fields (~50). I have a filter like : sale = Product.objects.filter(id=2) But this give me all 50 fields for id = 2, so I tried to add only to reduce the queryset size since I only need 2 fields: sale = Product.objects.filter(id=2).only("Origin","Price") Now I want to access to the price with sale.Price but I have the error 'QuerySet' object has no attribute 'Price' -
Convert a list of dictionary to a list of tuples
I have a requirement where I am getting data from DB in a certain format (List of dictionary), but the next set of methods require data in a certain format (List of tuples). How to convert it. The input format is [{'approximate_age_band': ['80-89', '70-79', '60-69'], 'state': ['WY', 'WV', 'WI', 'WA'], 'relationship': ['DEPENDENT', 'SELF', 'SPOUSE'], 'gender': ['Female', 'Male'], 'attribute1_name': ['Medical Plan Type', None], 'attribute1_value': ['POS', None], 'attribute2_name': ['Company Code'], 'attribute2_value': ['M110', None], 'attribute3_name': ['Business Unit', None], 'attribute3_value': ['00001009', '0000444', None], 'attribute4_name': ['Employee Type'], 'attribute4_value': ['Permanent'], 'attribute5_name': [None], 'attribute5_value': [None]}] The output format which I need from this data is [('approximate_age_band', '80-89'), ('approximate_age_band', '70-79'), ('approximate_age_band', '60-69'), ('state', 'WY'), ('state', 'WV'), ('state', 'WI'), ('state', 'WA'), ('relationship', 'SPOUSE'), ('relationship', 'SELF'), ('relationship', 'DEPENDENT'), ('gender', 'Male'), ('gender', 'Female'), ('attribute1_name', 'Medical Plan Type'), ('attribute1_value', 'POS'), ('attribute2_name', 'Company Code'), ('attribute2_value', 'M110'), ('attribute3_name', 'Business Unit'), ('attribute3_value', '00001009'), ('attribute3_value', '0000444'), ('attribute4_name', 'Employee Type'), ('attribute5_name', ''), ('attribute5_value', '')] Can someone please help me with finding the solution. -
Deploying Django, Django REST Framework backend & VueJS + webpack frontend on GCP App Engine (standard)
I have following setup: Django==3.1.4 djangorestframework==3.12.2 django-webpack-loader==0.7.0 (I am not convinced to use this - but this is separate story - just doing some learning for fun) On local dev setup everything works fine. Webpack-loader finds and deploys VueJS application. But when deployed to GAE following error is thrown: Error reading /workspace/frontend/webpack-stats.json. Are you sure webpack has generated the file and the path is correct? it comes from: /layers/google.python.pip/pip/lib/python3.9/site-packages/webpack_loader/loader.py, line 28, in load_assets I read tones of tutorials. All is clear when running on local dev - starting both django and VueJS. Of course, the problem is that webpack-stats.json are not created, as VueJS server is not started. I tried to find proper solution for this, but failed. I tried as well having VueJS on just domain with statics - but failed as well. What is best solution to have basic VueJS app talking to REST CRUDS and run it on GAE? -
Django timezone won't record user's timezone
So I just deployed a django web app but to my surprise, it records all time objects with UTC +0. ALL OF THEM! no matter the user's timezone. I have USE_TZ = True in settings. Here are the places I'm inserting time. Model.py class Timesheet(models.Model): .... start_date = models.DateTimeField(default=timezone.now) .... def save(self, *args, **kwargs): entry = Timesheet.objects.filter(id=self.request.user) if entry.exists(): Timesheet.objects.filter(id=self.request.user).update(end_date=timezone.now()) ... super().save(*args, **kwargs) How do I make it use the timezone of the user all across U.S.? -
saving data into a two table tables at the same time with a single form
I would like to save data in two tables at the same time using a single form in Django. Any help would be appreciated. class Category(models.Model): name = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return self.name class Stock(models.Model): id = models.AutoField(primary_key=True) category = models.ForeignKey(Category, on_delete=models.CASCADE,blank=True) item_name = models.CharField(max_length=100, blank=True, null=True) quantity = models.IntegerField(default='0',blank=True, null=True) class StockHistory(models.Model): id = models.AutoField(primary_key=True) category = models.ForeignKey(Category, on_delete=models.CASCADE,blank=True) item_name = models.CharField(max_length=100, blank=True, null=True) quantity = models.IntegerField(default='0',blank=True, null=True) -
Issues saving multiple database objects when iteration over a dictionary
I have an issues that has been making me tear my hair out for a while now. I have a simple Django app built with Django Rest Framework that interfaces with a Cassandra backend using django-cassandra-engine. I have set up a rest endpoint that accepts JSON data that is formatted like so: { "id": "47819417-d305-49b4-9e47-5fc554228438", "device": "TestDevice", "readings": [ { "id": "92e448d2-fd89-4eb3-ab1a-cdaf2056963a", "name": "testValue1", "value": "35" }, { "id": "6d79924a-1221-46c2-a3a6-4b667d85a7b6", "name": "testValue2", "value": "64" } ] } The format of this JSON is fixed, the only variable is the amount of readings that it contains. In my database, I am storing one reading per line - so one record would have device_id (which is obtained from elsewhere in the system), device, name, value, origin and id. This means that the above example should produce two records in the database. When I receive it, I do the following processing: @api_view(['POST']) def import(request): if request.method == 'POST': event_data = JSONParser().parse(request) # Check to see if the device exists in the metadata and retrieve the ID try: device = DeviceMetadataByID.objects.filter(device_name=event_data["device"]) device_id = getattr(device[0], 'device_id') except IndexError: # If not, retrieve the device description and ID from the Edge database url = "http://192.168.1.131:48081/api/v1/device/name/" + … -
What is the best way to optimize the performance of those Django QuerySet?
I have this function that generate data for a HighChart chart. But it is very very very slow. It take 2.3 seconds to generate only 1 device for 24 hours even if there is no data at all in the Database. I normally have between 10 and 100 device to chart! Is there anyway to optimize those querySet ? def getVacChart(self, fromDate, toDate): if((toDate - fromDate).days <= 1): avgMinutes = 15 elif((toDate - fromDate).days <= 2): avgMinutes = 30 elif((toDate - fromDate).days <= 3): avgMinutes = 45 else: avgMinutes = 60 totalReadings = int(((toDate - fromDate).total_seconds() / 60) / avgMinutes) readings = self.vacReading.filter(timeStamp__gte = fromDate).filter(timeStamp__lte = toDate).order_by('timeStamp') i = 0 _from = fromDate + datetime.timedelta(minutes = (i * avgMinutes)) _middle = int(round((_from + datetime.timedelta(minutes = (avgMinutes / 2)) - datetime.datetime.fromtimestamp(0)).total_seconds())) * 1000 _to = _from + datetime.timedelta(minutes = avgMinutes) data = [] if(toDate > datetime.datetime.now()): stop = datetime.datetime.now() else: stop = toDate lastAvgRdg = None while _from <= stop: avgRdg = readings.filter(timeStamp__gte = _from).filter(timeStamp__lte = _to).aggregate(Avg('vacuum'))["vacuum__avg"] if(avgRdg is not None): avgRdg = round(avgRdg, 1) lastAvgRdg = avgRdg else: if(lastAvgRdg is not None): avgRdg = lastAvgRdg data.append([_middle, avgRdg]) i += 1 _from = fromDate + datetime.timedelta(minutes = (i * avgMinutes)) _middle … -
How to add groups listbox to user update from?
I've created a ModelForm in Django to update users. I would like to also use this form to change which groups the user is a member of. However, I cannot work out how to add groups field to my form. I think this is because of how the M2M relationship between user and groups is setup in Django, that I cannot access the widget from the user side. This seems like it should be quite a common problem. Is there an obvious solution that I am missing? My form currently looks like this: class UserUpdateForm(forms.ModelForm): username = forms.CharField(error_messages={'invalid': '150 characters or fewer. Letters, digits and ./+/-/_ only.'}) id_role = forms.ModelMultipleChoiceField(queryset=Roles.objects.all(), widget=forms.CheckboxSelectMultiple()) class Meta(): model = User fields = ('__all__') -
How to use Django shell to interact with running server?
In the apps.py of one of my apps I set some class variables for models that can't be set at initialization because they depend on other apps and the models in them. This works fine and the class variables are set, but what I want to do is then test these classes to see if they'll work as intended. My problem is the class variables are set when I run the development server, but I want to also be able to create new instances of these models for testing. I realize that this can be accomplished by building the front-end that will interact with the models in production, but this seems to be excessive for simple testing. Is there a way to use Django's shell on a currently running server, or do I have to go through importing and running all the things that manage.py usually takes care of on its own? In case what I have written isn't clear, here's an example of the files in question: # example.models.py from django.db.models import * class ExampleModel(Model): class_var = None . . . # apps.py from django.apps import AppConfig class ExampleConfig(AppConfig): name = 'example' def ready(self): from example.models import ExampleModel ExampleModel.class_var … -
Django Database - create a table that has three foreign keys from two other separate tables
I'm creating a database that has the following criteria: Table 1: each restaurant has a unique restaurant id Table 2: each restaurant id has many serving times (9 am-11 am) Table 3: a unique restaurant id that has its unique serving time has many food categories Table 4: a unique restaurant id that has its unique serving time and its unique food category have many food items Table 5: a unique restaurant id that has its unique serving time, unique food category, and its unique food item have one food item details I tried to include and exclude the foreign keys in the serializers.py, but the program does not work in both scenarios. I also tried different related_name in model.py (with and without %class). My whole database did not have any error, except a programming error occurs when I go to the Django admin site and click table 3. model.py class Restaurant_ID(models.Model): restaurant_id = models.CharField(unique=True, max_length=20) class Meta: verbose_name_plural = '1 Restaurant IDs' def __str__(self): return str(self.restaurant_id) class Restaurant_serving_times(models.Model): restaurant_id = models.ForeignKey(Restaurant_ID, on_delete=models.CASCADE) serving_time_hour = models.CharField(max_length=2, choices=Hours,default='8') serving_time_minutes = models.CharField(max_length=2, choices=Minutes,default='00') class Meta: verbose_name_plural = '3-1 Restaurant ID Serving Times' def __str__(self): return str(self.restaurant_id) class Serving_time_categories(models.Model): restaurant_id = models.ForeignKey(Restaurant_ID, on_delete=models.CASCADE) … -
How can i Show active in current page in pagination in django
Accually, i am facing all active in the list of page number on the buttom. But i want that only current page should be shown as active. i query the database as pagination and measure how much page needed. And then i make a list of pages. the list is called in template file make as a loop. views.py def index(request): Product_Details_all = Product_Details.objects.all().order_by('-id') # pagination p = Paginator(Product_Details_all, 15) # print(p.num_pages) number_of_pages = p.num_pages #show list of pages number_of_pages_1 = p.num_pages+1 list = [] for i in range(1, number_of_pages_1): list.append(i) page_num = request.GET.get('page', 1) try: page = p.page(page_num) except EmptyPage: page = p.page(1) context2 = {'Product_Details_all':page, 'list':list} return render(request, 'index.html', context2) template.html [![enter image description here][1]][1]{% if list %} <li> {% if Product_Details_all.has_previous %} <a href="{% url 'index' %}?page={{Product_Details_all.previous_page_number}}" class="prev" title="previous page">&#10094;</a> {% endif %} </li> {% for i in list %} <li> <a href="{% url 'index' %}?page={{i}}" class="active">{{i}}</a> </li> {% endfor %} <li> {% if Product_Details_all.has_next %} <a href="{% url 'index' %}?page={{Product_Details_all.next_page_number}}" class="next" title="next page">&#10095;</a> {% endif %} </li> {% endif %}``` -
Django URL shows previous and current page but I want only current page name in URL
Suppose currently I'm on the "http://127.0.0.1:8000/message/detailmessage/5" page and I want to go to "login" page by clicking on login hyperlink from base.html(nav-bar), I want it to show "http://127.0.0.1:8000/login" but it showing "http://127.0.0.1:8000/message/detailmessage/login" what should I do? base.html <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <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://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> <style> {% block css %}{% endblock %} </style> <title>{% block title %}{% endblock %}</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Home</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation" > <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavDropdown"> {% for id in doctor %} {{id.doctor_id}} {% endfor %} <ul class="navbar-nav ml-auto"> {% for id in doctor %} {{id.doctor_id}} <li class="nav-item"> <a class="nav-link" href=message/{{id.doctor_id}}>Message</a> </li> {% endfor %} <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" > LogIn/LogOut </a> <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <a class="dropdown-item" href="login">Login</a> <a class="dropdown-item" href="/">Log Out</a> </div> </li> </ul> </div> </nav> {% block body %} {% endblock %} <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous" ></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous" ></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous" ></script> … -
Stripe IntegrationError: stripe.redirectToCheckout: You must provide one of lineItems, items, or sessionId
I've got a Django website and I'm trying to integrate Stripe using Django the Stripe API on the backend and Vue.js on the frontend. However, when I try to run the checkout link that's supposed to redirect me to the payment processing page, I get the following error: Error: IntegrationError: stripe.redirectToCheckout: You must provide one of lineItems, items, or sessionId. at new r (https://js.stripe.com/v3/:1:6143) at Js (https://js.stripe.com/v3/:1:165350) at $s (https://js.stripe.com/v3/:1:165646) at https://js.stripe.com/v3/:1:166758 at Qs (https://js.stripe.com/v3/:1:166769) at nc (https://js.stripe.com/v3/:1:167275) at Ec.redirectToCheckout (https://js.stripe.com/v3/:1:188030) at http://localhost:8000/dashboard/myaccount/teams/plans/:342:39 Here's the Vue.js method responsible for this: <script src="https://js.stripe.com/v3/"></script> <script> const PlansApp = { data() { return { } }, delimiters: ['[[', ']]'], methods: { subscribe(plan) { console.log('Subscribe:', plan); const stripe = Stripe('{{ stripe_pub_key }}'); fetch('/dashboard/myaccount/teams/api/create_checkout_session/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' }, body: JSON.stringify({ 'plan': plan }) }) .then(function(response) { return response.json() }) .then(function(session) { console.log(session) return stripe.redirectToCheckout({ sessionId: session.sessionId }) }) .then(function(result) { if (result.error) { console.log('Error:', result.error.message) } }) .catch(function(error) { console.log('Error:', error); }); } } } Vue.createApp(PlansApp).mount('#plans-app') </script> And here's the Django code that creates the session on the backend: @login_required def create_checkout_session(request): stripe.api_key = settings.STRIPE_SECRET_KEY data = json.loads(request.body) plan = data['plan'] if plan == 'basic': price_id = … -
problem with multiple user dependent on each other in Django
I am working with some custom-made user models in Django. They are the following: myCustomeUser responsible for the primary identity of a user Industry is a user that will inherit the myCustomeUser Employee is another user account, which will inherit the myCustomeUser and Industry both my models.py: class myCustomeUser(AbstractUser): id = models.AutoField(primary_key=True) username = models.CharField(max_length=20, unique="True", blank=False) password = models.CharField(max_length=20, blank=False) is_Employee = models.BooleanField(default=False) is_Industry = models.BooleanField(default=False) class Industry(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='industry_releted_user') name = models.CharField(max_length=200, blank=True) owner = models.CharField(max_length=200, blank=True) license = models.IntegerField(null=True, unique=True) industry_extrafield = models.TextField(blank=True) Now I need to write the model of Employee. There are some conditions also: It should contain name, National ID, gmail, rank, employee_varified, named fields This will inherit the myCustomeUser and Industry both The Industry account user will primarily entry all the data of Employee in the database, except username and password(which are inherited from myCustomeUser) Later on, the Employee will search his National ID given by the Industry and finish the registration process by creating his username and password. I have tried the Employee model like this: class Employee(models.Model): user = models.ForeignKey(myCustomeUser,primary_key=True, null=True, on_delete=models.CASCADE) industry = models.ForeignKey(Industry, on_delete=models.CASCADE) National_ID = models.IntegerField(null=True, blank=False, unique=True) name = models.CharField(max_length=200, blank=False, null=True) gmail … -
POST image to django rest API always returns 'No file was submitted'
I am trying to get this working now for days -.- Using a simple NodeJS express server, I want to upload an image to a Django instance through Post request, but I just can't figure out, how to prepare the request and embed the file. Later I would like to post the image, created from a canvas on the client side, but for testing I was trying to just upload an existing image from the nodeJS server. app.post('/images', function(req, res) { const filename = "Download.png"; // existing local file on server // using formData to create a multipart/form-data content-type let formData = new FormData(); let buffer = fs.readFileSync(filename); formData.append("file", buffer); // appending the file a buffer, alternatively could read as utf-8 string and append as text formData.append('name', 'var name here'); // someone told me, I need to specify a name const config = { headers: { 'content-type': 'multipart/form-data' } } axios.post("http://django:8000/images/", formData, config) .then(response => { console.log("success!"); }) .catch(error => { console.log(error.response.data); // no file was submitted }); }); What am I doing wrong or did I miss something? -
how to do unit tests using Zeep on Django
i trying to using zeep on django to make test to a SOAP service, but always need to be running a runserver, but need to be executed without runserver because need to using a test database not a default database. i using like like this: def test_obtenerListaAcciones(self): # get actions # this server need to be up to work, but need to be execute test without work this. wsdl = 'http://127.0.0.1:8000/soap/getactions/' client = zeep.Client(wsdl=wsdl) headerArr = {} settings = Settings(strict=False, xml_huge_tree=True, extra_http_headers=headerArr, raw_response=True) client = Client(wsdl, settings=settings) action = self.test_create_actions() requestData = { } res = client.service.obtenerListaAcciones(**requestData)