Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
In Django using all auth i want to make a custom API without REST framework for following info i provided below
In this i will enter UID ,email,username using POSTMAN and it will check whether uid exist or not,if it exist it will login user,if it did not and if same email exist in User model,it will create entry for same email in social account table along with generating token,so user can login through social email id also.Can u explain me which method or what should i use to create all entries and generate token.I will also specify logintype in POSTMAN as like google or facebook.and if user does not exist in user table also,it will create new one using email and username -
GitLab CI with Django project and MS SQL Database cannot login
Have the following .gitlab-ci.yml: image: python:latest stages: - test services: - name: mcr.microsoft.com/mssql/server:2019-latest alias: mssql variables: ACCEPT_EULA: Y SA_PASSWORD: $SA_PASSWORD MSSQL_HOST: mssql SECRET_KEY: $SECRET_KEY DEBUG: "True" DB_NAME: $DB_NAME DB_USER: $DB_USER DB_PASSWORD: $DB_PASSWORD DB_HOST: mssql # This folder is cached between builds # http://docs.gitlab.com/ee/ci/yaml/README.html#cache cache: paths: - ~/.cache/pip/ before_script: - python -V - curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add - - curl https://packages.microsoft.com/config/ubuntu/20.04/prod.list > /etc/apt/sources.list.d/mssql-release.list - apt-get update -q && apt-get install nodejs build-essential libssl-dev libffi-dev python3-dev unixodbc-dev -yqq - apt-get install -y msodbcsql17 - apt-get install -y mssql-tools - pip install -r requirements.txt test: script: - python manage.py makemigrations - python manage.py migrate - python manage.py loaddata - python manage.py collectstatic - python manage.py test --keepdb With following error: System check identified some issues: File "/usr/local/lib/python3.9/site-packages/sql_server/pyodbc/base.py", line 312, in get_new_connection conn = Database.connect(connstr, django.db.utils.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)') Cleaning up file based variables 00:01 ERROR: Job failed: exit code 1 Anyone have a solution, made various changes all with the same error. The Login timeout expired is the persistent error, tried setting the DB_HOST to "127.0.0.1" with no success so far. -
how to search a slug in different table and add the item to Many-to-many field in orderItem table Django?
I want to add many different product table in OrderItem item field class OrderItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey( gamingpc, on_delete=models.CASCADE, blank=True, null=True) product = models.ForeignKey( PcComponent, on_delete=models.CASCADE, blank=True, null=True) -
Django migration already applied but I don't have the migration file
A migration was applied to the database, and the table "blacklist_id" exists (and is populated with rows.) I want to add a new Model and make a migration, but whenever I call makemigrations Django thinks that the blacklist_id model is new and attempts to make a migration for that, which causes an error. I don't want to remove the table from the server because it has data in it - what can I do? -
Django models objects return None
I have this model in my Django app. class Kilometer(models.Model): kilometers = models.IntegerField() It work when with a form I save data on my database (I can see the objects on the admin page) but I have issue when I want to access the data in django shell. >>> from forms.models import Kilometer >>> test = Kilometer(1) >>> print(test) Kilometer object (1) >>> print(test.kilometers) None I have the same problem with all my models. -
Change Meta with Rest API Javascript
I have a web app, where Django with Django-rest-framework is set as the backend and html+css+javascript on the frontend. And they communicate using RestAPI. So... My Django is available on the pages: 'domain.com/api' and 'domain.com/admin'. On the page 'domain.com' my frontend part is available. And my question is... Are there any ways to change Meta on the frontend using Django? And I also need analytics to see these Meta and in-browser searches show the description and title, that I got from my backend model. -
Dynamically pass arguments to objects.filter
I am pretty new to Django and I am trying to get a query set from a filter function. This filter function is supposed to be able to take 1 to 5 arguments and I am not sure how to handle that. I have not found anything here that might help me, so if you do know of some other question that might help please let me know. views.py: @api_view(('Get',)) def update(request, REQUEST): if request.method == "Get": requestlist = REQUEST.split('&') for keys in requestlist: if 'module' in keys: module = keys[8:] if 'value' in keys: value = keys[6:] if 'user' in keys: user= keys[5:] if 'time1' in keys: time1 = keys[6:] if 'time2' in keys: time2 = keys[6:] item = Post.objects.filter(name=Name, user=USER, ...) The full request string will look like name=NAME&value=VALUE&user=USER&time1=FIRSTTIME&time2=SECONDTIME but it could also be any combination of the individual variables like name&time1. Now I want to be able to do that with one filter method instead of creating like 2^5 for each different szenario. -
Django Python group by IP net mask
I need to group by all my Ip addresses in that database on subnet mask 24. form example a list of 192.168.1.1, 192.168.1.2 is should result in 192.168.1.1 another ip list should result in 192.168.2.1, 192.168.2.2 result 192.168.2.1 so it should result alway the first of a subnet 24 Its to bad bit I come not further than something like this but this is to stuped off me ips = Ip.objects.values("ip").annotate(Count("ip")) -
Attendance: How to retrieve data from models in table with DATES as table heads and STATUS as table body in DJANGO?
I want to display attendance data from students based on date as the head of the table and status as the body of the table but what I got is not as expected. This is the Result i got. But what i want is like this Expected Result I'm already stuck for days to figure it out, can anyone help me please. Presensi = attendance Mahasiswa = students Status Absen = attendance status Nama = name Tanggal Absen = attendance date Models.py class Mahasiswa(models.Model): nama = models.CharField(max_length=25) def __str__(self): return self.nama class Presensi (models.Model): mahasiswa = models.ForeignKey(Mahasiswa, on_delete=models.CASCADE ) tanggal_absen = models.DateField() class Meta: # db_table = 'absensi' unique_together = (("mahasiswa","tanggal_absen"),) STATUS_ABSENS = ( ('H', 'Hadir'), ('I', 'Izin'), ('S', 'Sakit'), ('A', 'Absen') ) status_absen = CharField(max_length=1, choices=STATUS_ABSENS, default='A') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return str(self.mahasiswa) Views.py def indexTanggal(request): dates = Presensi.objects.values('tanggal_absen').order_by().distinct() presensis = Presensi.objects.values('id','mahasiswa__id','mahasiswa__nama','tanggal_absen', 'status_absen').order_by('mahasiswa__id') dict = {} date_temp = [] presence = [] student_temp = [] b = {} c = [] for date in dates: dict['date'] = date['tanggal_absen'] date_temp.append(dict.copy()) for presensi in presensis: temp = None if presensi['mahasiswa__id'] not in student_temp: student_temp.append(presensi['mahasiswa__id']) for presensii in presensis: if presensii['mahasiswa__id'] == presensi['mahasiswa__id']: if temp is None: temp … -
Create or get default object in ForeignKey
I have a Model of User. I want to assign new field 'role' to all of these users, Role connects User and his permissions. Im trying to assign a default role that gives full acess to every existing and every new User, enabling admin to limit someones permissions by creating new Role. I have looked for possible solutions on Stack Overflow: How do you specify a default for a Django ForeignKey Model or AdminModel field? but they don't seem to work on Django 3.0. def default_role(): all_user_permissions = CustomPermission.objects.all().filter(available_for_user=True) return Role.objects.get_or_create(name=_("Unlimited"), permissions=all_user_permissions)[0] class CustomUser(BaseUser): ... role = models.ForeignKey('users.RoleRole', verbose_name=_('role'), related_name='users', on_delete=models.CASCADE, default=default_role) When trying to makemigrations i get: AttributeError: type object 'CustomUser' has no attribute 'default_role' -
After listing tasks, celery worker doesn't load anything and the task status is always pending
Celery.py file: from __future__ import absolute_import import os from celery import Celery from vortex import settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings") app = Celery("myapp") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) task.py file: from celery import shared_task @shared_task(bind=True) def debug_task1(xyz): print('Running a task using celery', str(xyz)) return True views.py (when server starts running then debug_task1() will be called) def hello(request): try: t = debug_task1.delay() print("task status:", t.status) print("task id:", t.id) print("task result:", t.result) settings.py CELERY_BROKER_URL = 'redis://127.0.0.1:6379' CELERY_TIMEZONE = TIME_ZONE CELERY_ACCEPT_CONTENT = ["json"] CELERY_ENABLE_REMOTE_CONTROL = True CELERY_RESULT_SERIALIZER = "json" CELERY_RESULT_CACHE_MAX = -1 CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379' CELERY_TASK_ANNOTATIONS = { "celery.chord_unlock": {"soft_time_limit": 300, "default_retry_delay": 5} } CELERY_TASK_RESULT_EXPIRES = 600 CELERY_TASK_TRACK_STARTED = True CELERY_TASK_SERIALIZER = "json" CELERY_TASK_ACKS_LATE = True CELERY_TASK_SEND_SENT_EVENT = True CELERY_TASK_REJECT_ON_WORKER_LOST = True CELERY_TASK_ALWAYS_EAGER = False CELERY_WORKER_PREFETCH_MULTIPLIER = 1 CELERY_WORKER_POOL_RESTARTS = True CELERY_WORKER_HIJACK_ROOT_LOGGER = False CELERYD_TASK_TIME_LIMIT = 24 * 3600 # A task can run for max of 24hrs CELERYD_SEND_EVENTS = True CELERYD_MAX_TASKS_PER_CHILD = 20 CELERYD_WORKER_LOST_WAIT = 59 Server result: Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. task status: PENDING task id: 79e35cf7-0a3d-4786-b746-2d3dd45a5c16 task result: None worker result: -------------- celery@XYZ v5.0.5 (singularity) #XYZ is the system name --- ***** ----- -- ******* ---- Windows-XXX 2021-07-02 13:10:54 - *** --- * --- - ** ---------- … -
How to implement 'save' button and a list of saved objects in Django?
My page looks like that When i click 'save' it should be saved in 'saved' page(a list of saved books) models.py class Book(models.Model): LANGUAGES = ( ('ukr', 'Ukrainian'), ('eng', 'English'), ('rus', 'Russian'), ) image = models.ImageField(upload_to='images/', default='4.jpg') title = models.CharField(max_length=128) description = models.CharField(max_length=512) language = models.CharField(choices=LANGUAGES, default='English', max_length=100) # many books has one genre, if genre is deleted then delete related books genre = models.ForeignKey('Genre', on_delete=CASCADE) price = models.DecimalField(validators=[isBiggerThanZero], max_digits=6, decimal_places=2) slug = AutoSlugField(populate_from='title', default='') def __str__(self): return self.title class Genre(models.Model): genre = models.CharField(max_length=32, default='') def __str__(self): return self.genre -
Google cloud run cannot reach with Cloud SQL
Everything was working fine just a moment ago but suddenly Google cloud run cannot connect with Cloud SQL. Both Cloud Run and cloud SQL are in same project. Cloud SQL has public access. Cloud run is running a containerized Django/uwsgi/nginx application. Getting following error: MySQLdb._exceptions.OperationalError: (2003, "Can't connect to MySQL server on 'xx.xxx.xx.xxx:3306' (110)") Below is the cloud run yaml piece: annotations: run.googleapis.com/client-name: gcloud client.knative.dev/user-image: my_custom_manage run.googleapis.com/client-version: 347.0.0 run.googleapis.com/cloudsql-instances: my_project_id:us-central1:my_sql_server autoscaling.knative.dev/maxScale: '10' run.googleapis.com/sandbox: gvisor I have also followed this - https://cloud.google.com/sql/docs/mysql/connect-run and given my service account access to following- Service-account - my_service_account@project-id.iam.gserviceaccount.com has below permission: Cloud SQL Admin Cloud SQL Client Cloud SQL Editor Storage Admin This service account is added as a member in Cloud run service with Cloud Run Admin role. -
Django: ajax dropdown URL to retrieve data
I have a working ajax dropdown list as shown below. I notice its URL doesn't change with my dropdown selection. I will eventually need to create a view button that reads what is selected and proceed to display a table below. I am planning to read what is selected from the dropdown URLs and then passing it through views.py. However, my ajax dropdown is not giving me any URLs in the first place. main.js const selectedNodeStack = document.getElementById("nodeDropdown") const selectedNameStack = document.getElementById("nameDropdown") const selectedstackname = document.getElementById("stackDropdown") const nameText = document.getElementById('name-text') const stackText = document.getElementById('stack-text') $.ajax({ type:'GET', url: '/techNode/', success: function(response){ //get the data from 'data' defined in views console.log(response.data) const testData = response.data testData.map(item=>{ const optionElement = document.createElement('option') optionElement.value = item.node optionElement.text = item.node selectedNodeStack.appendChild(optionElement); }) }, error: function(error){ console.log(error) } }); $('#nodeDropdown').change(function(){ console.log("Changed") console.log(document.getElementById("nodeDropdown").value) const selectedNode = document.getElementById("nodeDropdown").value selectedNameStack.innerHTML = "" nameText.textContent = "Select a name" $.ajax({ type:'GET', url: `techName/${selectedNode}/`, success: function(response){ console.log(response.data) const testData = response.data testData.map(item=>{ const optionElement = document.createElement('option') optionElement.value = item.name optionElement.text = item.name selectedNameStack.appendChild(optionElement); }) }, error: function(error){ console.log(error) } }) }) $('#nameDropdown').change(function(){ console.log("Changed") console.log(document.getElementById("nameDropdown").value) const selectedName = document.getElementById("nameDropdown").value selectedstackname.innerHTML = "" stackText.textContent = "Select a stackname" // stackname dropdown $.ajax({ type:'GET', url: `stackName/${selectedName}/`, … -
Why am I not getting a default value when I pass a function to the default parameter in model field definition?
I have a model Package, that has a field named max_fractions, I want this field to be prepopulated when the user fills two other fields of the same model. Here is the model: class Package(models.Model): rt_number=ForeignKey(Patient, on_delete=CASCADE) diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE) treatment=ForeignKey(Treatment, on_delete=CASCADE) patient_type=ForeignKey(PatientType, on_delete=CASCADE) max_fractions=models.IntegerField(default=funcs.max_fractions(treatment, patient_type), blank=True) total_package=models.DecimalField(max_digits=10, decimal_places=2) I want the max_fractions field to be prefilled the user selects the options for treatment and patient_type. I have passed the following function as the default parameter: def max_fractions(tt, ptt): #VMAT/RAPID ARC if tt=='VMAT/RAPID ARC' and ptt=='MJPJAY': return 40 if tt=='VMAT/RAPID ARC' and ptt=='MJPJAY/PC': return 40 if tt=='VMAT/RAPID ARC' and ptt=='Cash': return 40 forms.py: class PackageForm(ModelForm): class Meta: model=Package fields='__all__' views.py: def package_view(request): if request.method=='POST': fm_package=PackageForm(request.POST) fm_diagnosis=DiagnosisForm(request.POST) fm_treatment=TreatmentForm(request.POST) fm_patient_type=PatientTypeForm(request.POST) if fm_package.is_valid() and fm_diagnosis.is_valid() and fm_treatment.is_valid() and fm_patient_type.is_valid(): diagnosis=fm_diagnosis.save() treatment=fm_treatment.save() patient_type=fm_patient_type.save() package=fm_package.save(False) package.diagnosis=diagnosis package.treatment=treatment package.patient_type=patient_type package.save() fm_package=PackageForm() fm_diagnosis=DiagnosisForm() fm_treatment=TreatmentForm() fm_patient_type=PatientTypeForm() return render (request, 'account/package.html', {'form2':fm_diagnosis, 'form3':fm_treatment, 'form4':fm_patient_type, 'form5':fm_package}) else: fm_package=PackageForm() fm_diagnosis=DiagnosisForm() fm_treatment=TreatmentForm() fm_patient_type=PatientTypeForm() return render (request, 'account/package.html', {'form2':fm_diagnosis, 'form3':fm_treatment, 'form4':fm_patient_type, 'form5':fm_package}) Help me out here, please! -
How can add product to the cart using ajax in django?
Problem I want to add the product to the cart using ajax so that the page is not reloaded or refreshed and a popup is shown that the product is added to the cart. Script $(document).on("click",".Id_submit",function(event){ event.preventDefault(); var selector = $(this).closest(".productID") console.log(selector.find("form").attr('action')) $.ajax({ type : 'POST', url: selector.find("form").attr('action'), success: function() { alert("Product added to cart") } }); html <form id='transactionIDValue' class="d-inline" method="post"> {{cart_product_form}} {% csrf_token %} <input type="submit" class="btn btn-primary shadow px-5 py-2 Id_submit" value="Add To Cart"> </form> views.py @require_POST def cart_add(request, product_id): cart = Cart(request) product = get_object_or_404(transactions, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart.add(product=product, quantity=cd['quantity']) print(cart) # request.session['items_total'] = cart.product.count() return HttpResponse('success') urls.py extra_patterns = [ path('add/carts/<int:product_id>/', views.cart_add, name='cart_add'), ] urlpatterns=[ path ('add/',include(extra_patterns)), ] The issue I'm facing is that using the script it goes the cart url but the product is not added and in the console it shows that the url is forbidden. So, can someone help me with this issue please. -
Receiving an error when installing bootstrap4
I'm trying to install django-bootstrap4 on Python, but I'm not sure how to deal with this error. Issued the command, 'pip install django-bootstrap4' in my virtual environment. error ImportError: cannot import name 'SCHEME_KEYS' from 'pip._internal.models.scheme' (c:\users\chawa\onedrive\desktop\learning_log\ll_env\lib\site-packages\pip\_internal\models\scheme.py) Python version - 3.8.5 Django version - 3.2.4 -
CreateView ModelForm multiple record once
My page has questions and options. Everything seems to be ok in the source as HTML. but I can't register. All questions depend on a single submit. I am using createview. I have override form_valid in Class. However, I could not save. ... def form_valid(self, form): self.object = form.save(commit=False) for sr in range(self.form['soruadet']):#<-question amount from page with post self.object.soru_id = self.form['soru-'+sr] self.object.cevap_id = self.form['cevap-' + sr] self.object.useris = self.form['useris'] self.object.save() return HttpResponseRedirect(self.get_success_url()) ... -
Redirect to a view with parameters upon form submission in Django
How to redirect to a new page upon form submission, using information gathered from the form? Currently, the page renders correctly when accessed from a different URL by typing out that URL along with its parameters. But of course this isn't intuitive, so the goal is ideally the parameters come from a form and when submitted goes to the page with this parameters in mind? filter-form.html: ... <form> <label for="item">Item:</label> <select id="item" name="item"> <option value="all">All</option> <option value="filtered">Filtered</option> </select> <label for="category">Category:</label> <select id="category" name="category"> <option value="new">New</option> <option value="used">Used</option> </select> <label for="start_date">Start Date:</label> <input type="date" id="start_date" name="start_date"/> <label for="end_date">End Date:</label> <input type="date" id="end_date" name="end_date"/> <button id="filter-button">Filter</button> </form> ... urls.py: ... urlpatterns += [ # home page of the form path('item/', views.item), # this is the URL the form goes to when the `filter-button` is pressed path('item/?item=<str:item>&category=<str:category>&start_date=<str:start_date>&end_date=<str:end_date>', views.filter_items), # a direct way to visit the result site, type this url out and it renders the correct page and context path('item/list/<str:item>/<str:category>/<str:start_date>/<str:end_date>/', views.list_items), ] ... views.py: def list_items(response, item, category, start_date, end_date): ... context = { 'item': item, 'category': category, 'start_date': start_date, 'end_date': end_date } return render(response, views/item_list.html, context) Now here comes what I've tried so far, with no success: views.py>filter_items: def filter_items(response, item, category, … -
Show item details together with item name in forms dropdown
currently I'm trying to show part quantity (quan) together with part name in the dropdown. I have a Part table that carries the part name and part quantity and this table called as ForeignKey into the Order table. So, in the Order form during choose the part name from the part dropdown, I would like to show part quantity as well besides the part name. Any idea to make it like that? models.py class Part(models.Model): partno = models.CharField(max_length=50) partname = models.CharField(max_length=50) quan = models.PositiveIntegerField(default= 0) class Order(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) part = models.ForeignKey(Part, on_delete=models.CASCADE) views.py def create_order(request): from django import forms form = OrderForm() if request.method == 'POST': for form_data in forms_data: forms = OrderForm(request.POST) if forms.is_valid(): supplier = forms.cleaned_data['supplier'] product = forms.cleaned_data['product'] part = forms.cleaned_data['part'] order = Order.objects.create( supplier=supplier, product=product, part=part, ) return redirect('order-list') context = { 'form': form } return render(request, 'store/addOrder.html', context) HTML <form action="#" method="post" id="form-container" novalidate="novalidate"> {% csrf_token %} <div class="form-group"> <label for="product" class="control-label mb-1">Product</label> {{ form.product }} </div> <div class="form-group"> <label for="supplier" class="control-label mb-1">Supplier</label> {{ form.supplier }} </div> <div class="form-group"> <label for="part" class="control-label mb-1">Part Name</label> {{ form.part }} </div> </form> -
POST API request not working from browser but working fine on Postman. Throws AssertionError in browser to call is_valid() before accessing .data
Ok, Here's the problem: I have created a POST API in Django REST framework & I want to add logged-in user to request.data when making POST request & It works perfectly fine when I create post calling this API from Postman, but when I visit the post create API endpoint from browser it throws AssertionError: '''When a serializer is passed a data keyword argument you must call .is_valid() before attempting to access the serialized .data representation. You should either call .is_valid() first, or access .initial_data'''. Here's the snippet of my get_serializer method which i use to override & add user to request.data: class PostCreateView(CreateAPIView): serializer_class = PostSerializer def get_serializer(self, *args, **kwargs): serializer_class = self.get_serializer_class() kwargs["context"] = self.get_serializer_context() request_data = self.request.data.copy() request_data["user"] = self.request.user.id kwargs["data"] = request_data return serializer_class(*args, **kwargs) def post(self,request): serializer = self.get_serializer() serializer.is_valid(raise_exception=True) serializer.save() status_code = status.HTTP_201_CREATED response = { 'success' : 'True', 'status code' : status_code, 'message': 'Post created successfully', 'post_detail': serializer.data, } return Response(response, status=status_code) -
TypeError 'set' object is not reversible
I saw similar in discussions they all suggested to replace {} by []. But, I used [] itself in url patterns. please find the error!! here is the error in google chrome Code : layout.html <!DOCTYPE html> <html lang="en"> <head> <title>Tasks</title> </head> <body> {% block body %} {% endblock %} </body> </html> add.html <!DOCTYPE html> <html lang="en"> <head> <title>Tasks</title> </head> <body> {% block body %} {% endblock %} </body> </html> urls.py from django.urls import path from . import views app_name = "tasks" urlpatterns = [ path("", views.index, name="index"), path("add", views.add, name="add") ] **index.html** {% extends "tasks/layout.html" %} {% block body %} <ul> {% for task in tasks %} <li>{{ task }}</li> {% endfor %} </ul> <a href="{% url 'tasks:add' %}">Add a New Task</a> {% endblock %} -
AttributeError: Got AttributeError when attempting to get a value for field `name` on serializer `BinbaseBlacklistCreateSerializer`
Here is my code: views.py class BinbaseBlacklistAPIView(ListCreateAPIView): serializer_class = BinbaseBlacklistListSerializer permission_list = ['Can view binbase blacklist rules', 'Can add new binbase blacklist rules', 'Can edit binbase blacklist rules'] related_permissions = [] pagination_class = None permission_classes = (IsAuthenticated,) def get_permissions(self): permissions = super().get_permissions() permissions.append(HasPermission(self.permission_list, related_permissions=self.related_permissions)) return permissions def get_serializer_class(self): if self.request.method == 'POST': return BinbaseBlacklistCreateSerializer return BinbaseBlacklistListSerializer def get_queryset(self): return BinbaseBlacklistRule.objects.all() def put(self, request, *args, **kwargs): pass class BinbaseBlacklistEditDeleteView(RetrieveUpdateDestroyAPIView): serializer_class = BinbaseBlacklistCreateSerializer permission_list = ['Can view binbase blacklist rules', 'Can add new binbase blacklist rules', 'Can edit binbase blacklist rules'] permission_classes = (IsAuthenticated,) queryset = BinbaseBlacklistRule.objects.all() def get_permissions(self): if not self.request.user or not self.request.user.id: raise NotAuthenticated({'detail': 'Authentication credentials were not provided.'}) pk = self.kwargs.get('pk') rule = BinbaseBlacklistRule.objects.filter(pk=pk).first() if not rule: raise ValidationError('Rule id %s not found' % pk) permissions = super().get_permissions() permissions.append(HasPermission(self.permission_list)) return permissions def delete(self, request, *args, **kwargs): BinbaseBlacklistRule.objects.filter(id=kwargs.get('pk')).delete() return super().delete(request, *args, **kwargs) serializers.py class BinbaseBlacklistListSerializer(serializers.ModelSerializer): class Meta: model = BinbaseBlacklistRule fields = '__all__' class BinbaseBlacklistCreateSerializer(serializers.ModelSerializer): binbase_blacklist = BinbaseBlacklistListSerializer(many=True, read_only=True) class Meta: model = BinbaseBlacklistRule fields = '__all__' def create(self, validated_data): name = validated_data.pop('name') is_active = validated_data.pop('is_active') merchants = ast.literal_eval(validated_data.pop('merchant_ids')) bin_data = ast.literal_eval(validated_data.pop('bins')) return BinbaseBlacklistRule.objects.get_or_create(name=name, is_active=is_active, merchant_ids=merchants, bins=bin_data) I am trying to get data and create or get existing object … -
Multiple different database Connectivity with Django
Iam working in a django project.Here i need a help to connect multiple different database engines like mongo and mysql.Also please help me how to configure in django settings. -
CommandError in django while using call_command(startapp, app_name)
I want to create a Django app from user input. Here is my code. def createAppname(name): split_name = name.split(" ") s = "".join(i[0:] for i in split_name) return s def formFields(request): if request.method == 'POST': app_name = request.POST.get('app') new_name=createAppname(app_name) from django.core.management import call_command call_command('startapp', new_name) return render(request,'forms_new.html') return render(request, 'forms_new.html') The code works perfectly when I am executing in the development environment. But after deploying on the production server, here I'm using apache_mod_wsgi, I get the following error. Traceback (most recent call last): File "/path/to/env/lib/python3.6/site-packages/django/core/management/templates.py", line 70, in handle os.makedirs(top_dir) File "/path/to/env/lib/python3.6/os.py", line 220, in makedirs mkdir(name, mode) During handling of the above exception ([Errno 13] Permission denied: '/thisisnewappfromServer'), another exception occurred: File "path/to/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/path/to/env/lib/python3.6/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/rohit/Documents/Web_app/project/new_models/views.py", line 70, in formFields call_command('startapp', new_name) File "/path/to/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 168, in call_command return command.execute(*args, **defaults) File "/path/to/env/lib/python3.6/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/path/to/env/lib/python3.6/site-packages/django/core/management/commands/startapp.py", line 14, in handle super().handle('app', app_name, target, **options) File "/path/to/env/lib/python3.6/site-packages/django/core/management/templates.py", line 74, in handle raise CommandError(e) Exception Type: CommandError at /models/details/ Exception Value: [Errno 13] Permission denied: '/thisisnewappfromServer' Please help me out here. Thanks.