Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am getting error while installing web3 module in my django project
ERROR: Command errored out with exit status 1: command: 'C:\Users\saran\OneDrive\Desktop\interview\crypto\core\meta\Scripts\python.exe' -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\saran\\AppData\\Local\\Temp\\pip-install-j3khl3b4\\cytoolz_486c7a4bef2c4764b3179a18383f6bd7\\setup.py'"'"'; __file__='"'"'C:\\Users\\saran\\AppData\\Local\\Temp\\pip-install-j3khl3b4\\cytoolz_486c7a4bef2c4764b3179a18383f6bd7\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\saran\AppData\Local\Temp\pip-record-s5xwa9zp\install-record.txt' --single-version-externally-managed --compile --install-headers 'C:\Users\saran\OneDrive\Desktop\interview\crypto\core\meta\include\site\python3.10\cytoolz' cwd: C:\Users\saran\AppData\Local\Temp\pip-install-j3khl3b4\cytoolz_486c7a4bef2c4764b3179a18383f6bd7\ Complete output (49 lines): ALERT: Cython not installed. Building without Cython. running install running build running build_py creating build creating build\lib.win-amd64-3.10 creating build\lib.win-amd64-3.10\cytoolz copying cytoolz\compatibility.py -> build\lib.win-amd64-3.10\cytoolz copying cytoolz\_signatures.py -> build\lib.win-amd64-3.10\cytoolz copying cytoolz\_version.py -> build\lib.win-amd64-3.10\cytoolz copying cytoolz\__init__.py -> build\lib.win-amd64-3.10\cytoolz creating build\lib.win-amd64-3.10\cytoolz\curried copying cytoolz\curried\exceptions.py -> build\lib.win-amd64-3.10\cytoolz\curried copying cytoolz\curried\operator.py -> build\lib.win-amd64-3.10\cytoolz\curried copying cytoolz\curried\__init__.py -> build\lib.win-amd64-3.10\cytoolz\curried copying cytoolz\dicttoolz.pyx -> build\lib.win-amd64-3.10\cytoolz copying cytoolz\functoolz.pyx -> build\lib.win-amd64-3.10\cytoolz copying cytoolz\itertoolz.pyx -> build\lib.win-amd64-3.10\cytoolz copying cytoolz\recipes.pyx -> build\lib.win-amd64-3.10\cytoolz copying cytoolz\utils.pyx -> build\lib.win-amd64-3.10\cytoolz copying cytoolz\cpython.pxd -> build\lib.win-amd64-3.10\cytoolz copying cytoolz\dicttoolz.pxd -> build\lib.win-amd64-3.10\cytoolz copying cytoolz\functoolz.pxd -> build\lib.win-amd64-3.10\cytoolz copying cytoolz\itertoolz.pxd -> build\lib.win-amd64-3.10\cytoolz copying cytoolz\recipes.pxd -> build\lib.win-amd64-3.10\cytoolz copying cytoolz\utils.pxd -> build\lib.win-amd64-3.10\cytoolz copying cytoolz\__init__.pxd -> build\lib.win-amd64-3.10\cytoolz creating build\lib.win-amd64-3.10\cytoolz\tests copying cytoolz\tests\dev_skip_test.py -> build\lib.win-amd64-3.10\cytoolz\tests copying cytoolz\tests\test_compatibility.py -> build\lib.win-amd64-3.10\cytoolz\tests copying cytoolz\tests\test_curried.py -> build\lib.win-amd64-3.10\cytoolz\tests copying cytoolz\tests\test_curried_toolzlike.py -> build\lib.win-amd64-3.10\cytoolz\tests copying cytoolz\tests\test_dev_skip_test.py -> build\lib.win-amd64-3.10\cytoolz\tests copying cytoolz\tests\test_dicttoolz.py -> build\lib.win-amd64-3.10\cytoolz\tests copying cytoolz\tests\test_docstrings.py -> build\lib.win-amd64-3.10\cytoolz\tests copying cytoolz\tests\test_doctests.py -> build\lib.win-amd64-3.10\cytoolz\tests copying cytoolz\tests\test_embedded_sigs.py -> build\lib.win-amd64-3.10\cytoolz\tests copying cytoolz\tests\test_functoolz.py -> build\lib.win-amd64-3.10\cytoolz\tests copying cytoolz\tests\test_inspect_args.py -> build\lib.win-amd64-3.10\cytoolz\tests copying cytoolz\tests\test_itertoolz.py -> build\lib.win-amd64-3.10\cytoolz\tests copying … -
How to convert the image received with django request FILES into pdf
I saw many answers, but it was hard to find the answer I wanted. I don't want to find files locally and save them locally. I want to receive the image with request FILES and convert it directly into pdf. I'd appreciate it if you could give me an answer. Finally, I want to upload it to s3. def create(self): file = self.request.FILES.get('file', None) # image -> pdf # local save() No. ... Is there something wrong with the settings? # settings.py STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] # MEDIA_ROOT = os.path.join(BASE_DIR, 'media') DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' -
Get the name or labe from django IntegerChoices providing a valid value
I have django 3.2 and an IntegerChoices class class Type(models.IntegerChoices): GENERAL = 2, _("general address") DELIVERY = 4, _("delivery address") BILLING = 6, _("billing address") I can get the Value name and label easily by doing Type.GENERAL , Type.GENERAL.name and Type.GENERAL.label. But how can I get these values if I only have the value, e.g. I want to get the Name DELIVERY from the value 4. Type[4].name ist not working as the list values does not correspond to the int values of the enum. Thanks Matt -
how do I increase number of order detail without refreshing
I am beginner in Django, I create checkout page and when user on change input range number enter image description here it s send to server but it work for first one I think because I set same id for all input and I can t change it because it s in for tag how can I fix it? Django part class Ajax_Handler(View): def get(self,request): if request.is_ajax(): count=request.GET['count'] return JsonResponse({'count':count},status=200) ajax part $(document).ready(function(){ var crf=$('input[name=csrfmiddlewaretoken]').val(); $("#icount").change(function(){ $.ajax({ url:'/adding', type:'get', data:{ count:$('#icount').val(), }, success:function(respond){ $('#icount').val(respond.count) } }); }); }); html part <tbody> {% for order in order.orderdetail_set.all %} <tr> <td class="product-image"> {% thumbnail order.product.image "100x100" crop="center" as im %} <img src="{{ im.url }}" width="{{ im.width }}" height="{{ im.height }}"> {% endthumbnail %} </td> <td class="product-name"><a href="products/{{order.product.id}}">{{order.product.title}}</a></td> <td class="product-price">{{order.product.price|intcomma:False}}تومان</td> <td class="product-quantity"> <label>تعداد</label> <input type="hidden" name="order_id{{order.id}}" value="{{order.id}}"> <input name='count' id='icount' min="1" max="100" value="{{order.count}}" type="number"> </td> <td class="product-total">{{order.totalprice|intcomma:False}}</td> <td class="product-remove"><a href="delete/{{order.id}}"><i class="fa fa-trash-o"></i></a></td> </tr> {% endfor %} </tbody> -
For the two errors of updateview, Django
I will write down the code first and explain it below. views.py class comment_update(UpdateView): model = Comment fields = '__all__' # success_url = reverse_lazy('board') def get(self, request, pk): com = Comment.objects.filter(id=pk) return render(self.request, 'comment_edit.html',{ 'com' : com }) def get_success_url(self): return reverse('board_detail', kwargs={'pk':self.object.board.pk}) urls.py path('board/comment/<int:pk>/update/', views.comment_update.as_view(), name="comment_update") template <form action="{% url 'comment_update' i.id %}"> If i don't use fields in the situation as the code above, A Error occurs. When fields are used, an error of B occur. In the case of B, why does the success_url and get_sufficiency_url not work? A ImproperlyConfigured at /board/comment/4/update/ Using ModelFormMixin (base class of comment_update) without the 'fields' attribute is prohibited. B TemplateDoesNotExist at /board/comment/4/update/ board/comment_form.html -
How to use different key name in MongoDB while working with Django?
I am working on developing a micro service using Django, where I use MongoDB as backend. Folks who wrote the main code used java hence the data already present in the MongoDB collections follows camelcase pattern for e.g. firstName is the key name. Now while working with python I like to name my variables and functions using snake casing like first_name and get_first_name(). What I want is that inside the code I want to refer first name as first_name but while saving first name in DB or returning JSON response of user data I want to return it as firstName? Is there any way to achieve this behaviour? Please help me? -
Django Admin raise 500 error in production Heroku
I know this question was raised multiple times, but wasn't able to solve the problem. Here is my problem: my Django-React app is deployed on Heroku and works great (very simple app). I would like know to access the /admin part of my app, but I get a 500 Internal Server Error. The error appears locally and in Heroku. The DEBUG is False, and unfortunately I can't get the logs to work, neither in Heroku nor locally :( Here is my settings.py: from pathlib import Path import django_heroku import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'xxxxxxxxxxxxxxxxxxxxxx' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['vmbf.herokuapp.com', '127.0.0.1', 'localhost'] ADMINS = [('username', 'emailaddress')] MANAGERS = ADMINSEMAIL_HOST = 'host' SEND_BROKEN_LINK_EMAILS=True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'emailaddress' EMAIL_HOST_PASSWORD = 'password' EMAIL_PORT = 587 EMAIL_USE_TLS = True SERVER_EMAIL = EMAIL_HOST_USER # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'students', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', … -
django - q object filtering getlist
I want to make an intersection by bringing intelligence,strength, and charm from the stat variable to the getlist, but it only comes out as a combination. What could be the reason? I'm waiting for your help. class ProductListView(View): def get(self,request): category = request.GET.get('category', None) sub_category = request.GET.get('sub_category', None) stat = request.GET.getlist('stat', None) q=Q() if category: q &=Q(sub_category__category__name=category) if sub_category: q &=Q(sub_category__name=sub_category) if stat: q &=Q(coursestat__stat__name__in=stat) products = Course.objects.filter(q).distinct() results=[{ "course_id" : product.id, "thumbnail" : product.thumbnail_image_url, "user_name" : product.user.name, "sub_category" : product.sub_category.name, "course_name" : product.name, "price" : product.price, "payment_period" : product.payment_period, "course_like" : product.like_set.count() } for product in products] return JsonResponse({"results" : results}) The query parameters created by Postman are as follows. enter image description here -
How to get id from created object in Django
I have models: Group and Members. Group have many members, but when group is creating, currentUser is automaticlly member. I'm doing everything in single request and I have problem with getting id createdGroup. My models: class Group(models.Model): groupName = models.CharField(max_length=100) description = models.CharField(max_length=255) inviteKey = models.UUIDField(default=uuid.uuid4, unique=True, editable=False) class Members(models.Model): userId = models.ForeignKey(User, on_delete=models.CASCADE) groupId = models.ForeignKey(Group, on_delete=models.CASCADE) Form: class GroupForm(forms.ModelForm): groupName = forms.CharField(label='Name', max_length=100) description = forms.CharField(label='Description', max_length=255) inviteKey: forms.CharField(label='Invite Key') class Meta: model = Group fields = ['groupName', 'description'] View: def createGroup(request): if request.method == "POST": form = GroupForm(request.POST) if form.is_valid(): form.save() currentUser = request.user print('group id', request.POST.get('id', '')) #after group creation i would add current member addMember(currentUser, True, True) # should be currentUser, createdGroup, True messages.success(request, f'Group created') return redirect('/') else: form = GroupForm() return render(request, 'group/createGroup.html',{'form': form}) How i can reach newly created group's id? I've tried something like this: group = request.POST.get('id', '') When i console.log request.POST i'm getting only (name, description) -
Django or Flask for building API?
Well, I have a desktop app developed with Python, And this app will communicate with the database for getting some data that are used (i.e login system, Activation of the software ..etc). Now I've come up with which framework should I use Django or Flask? I really get confused about which one is better for my project. Now, let's talk about the API that I want to build( not a website and it doesn't have any views or front-end), They are very small, all I need is a web application that tells the desktop app whether the user request's data which will contain the user's account is registered on the database or not, The other one is for checking if the product key that user entered from the desktop app is valid or not in every run-time. let's keep in mind in the future if we want to develop a feature or change something. I saw some people recommend Django for being have a lot of functionality, in the other hand Flask doesn't and needs extra work. others say that Flask support API whereas Django does not. Flask vs Django look at the table And some people think that Django … -
Data Migration breaking in production when using bulk_update
My application is deployed on Digital Ocean's App Platform for Django. The database is PostgreSQL. The following data migration has run correctly in my local environment. In production it starts but never ends running, so the deploy is automatically cancelled. This data migration affects more or less 40.000 lines in the database. from django.db import migrations def link_answers_to_default_segment(apps, schema_editor): """Create a default segment for each company""" Company = apps.get_model('brand_score', 'Company') Segment = apps.get_model('brand_score', 'Segment') Answer = apps.get_model('brand_score', 'Answer') for company in Company.objects.all(): default_segment = Segment.objects.create(company=company, name='default') answers = Answer.objects.filter(participant__company=company) for answer in answers: answer.segment = default_segment Answer.objects.bulk_update(answers, ['segment']) class Migration(migrations.Migration): dependencies = [ ('brand_score', '0025_auto_20211209_1412'), ] operations = [ migrations.RunPython(link_answers_to_default_segment, reverse_code=migrations.RunPython.noop), ] -
Using Django-reversion in combination with Neo4j
In a project we are using django-reversion for version control. Is there a way to get this to work with neo4j or get the same functionality in another way. -
Amazon-pay-sdk-python CreateButtonSignature
I'm integrating amazon-pay-SDK-python for the web. I have done reading all documentation of amazon-pay, but I didn't get any idea about how to give or create a button signature in Frontend/backend code. Here is my code of frontend to create a button of amazon-pay One-time-checkout. If anyone implemented this, give your valuable answer.. <body> <div id="AmazonPayButton"></div> <script src="https://static-na.payments-amazon.com/checkout.js"></script> <script type="text/javascript" charset="utf-8"> amazon.Pay.renderButton('#AmazonPayButton', { // set checkout environment merchantId: 'merchant_id', publicKeyId: 'SANDBOX-xxxxxxxxxx', ledgerCurrency: 'USD', // customize the buyer experience checkoutLanguage: 'en_US', productType: 'PayAndShip', placement: 'Cart', buttonColor: 'Gold', // configure Create Checkout Session request createCheckoutSessionConfig: { payloadJSON: 'payload', // string generated in step 2 signature: 'xxxx' // signature generated in step 3 } }); </script> </body> -
code H10 while Deploying Django code to Heroku
2021-12-16T14:04:17.499957+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=phoneinf0.herokuapp.com request_id=4b00137c-bb8e-426d-b427-fff468ac7491 fwd="94.249.24.198" dyno= connect= service= status=503 bytes= protocol=https -
how to display data of that date of week. which data is exist on that day by using python django
I want to return a week data of date, if data is exist on that date from threading. If there is data of that date, it should appear in the data list, and if there is no data of that date then a blank list should appear. currently I have data in database only of 2 days but same data returning on all 7 days. class TotalExceedance(Thread): def __init__(self,site): Thread.__init__(self) self.site = site def run(self): currentDate = datetime.datetime.now().date() weekAgo = currentDate - datetime.timedelta(days=7) site_label = self.site.json()[0]["label"] week_exc_data = [] for i in range(1,8): total_exceedance = ExceedanceModel.objects.filter(site=site_label,dateTime__date__range=[weekAgo, currentDate]).all().values() day = weekAgo + datetime.timedelta(days=i) print(day) week_exce = total_exceedance,day week_exc_data.insert(0, len(week_exce)) print("week exc data :", week_exc_data) #thread start th2 = TotalExceedance(sites) th2.start() th2.join() getting this output : 2021-12-10 2021-12-11 2021-12-12 2021-12-13 2021-12-14 2021-12-15 2021-12-16 week exc data : [2, 2, 2, 2, 2, 2, 2] I am expecting output like this : 2021-12-10 week exc data : [] 2021-12-11 week exc data : [] 2021-12-12 week exc data :[{'dateTime': '2021-12-12T08:55:00Z', 'site': 'ABCP', 'station': 'ABCP_1', 'parameter': 'COD', 'values': 5000.0}] 2021-12-13 week exc data : [] 2021-12-14 week exc data : [] 2021-12-15 week exc data : [{'dateTime': '2021-12-15T08:55:00Z', 'site': 'ABCP', 'station': 'ABCP_1', 'parameter': 'COD', … -
Delete all documents in a MongoDB collection via Django backend and Angular frontend
I have managed to write code to add a customer to my MongoDB collection from my Angular service method to my Django http function, as follows: const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Accept': 'application/json' }), withCredentials: false } @Injectable() export class MongoService { myApiBaseUrl = "http://localhost:8000/mydjangobaselink/"; constructor(private httpClient: HttpClient) { } addCustomer(customerFormInfo: Customer): Observable<Customer> { return this.httpClient.post<Customer>(`${this.myApiBaseUrl}`, JSON.stringify(customerData), httpOptions); } deleteCustomer(): Observable<Customer> { return this.httpClient.delete<Customer>(`${this.myApiBaseUrl}`); } } @csrf_exempt @api_view(['GET', 'POST', 'DELETE']) def handle_customer(request): if request.method == 'POST': try: customer_data = JSONParser().parse(request) customer_serializer = CustomerModelSerializer(data=customer_data) if customer_serializer.is_valid(): customer_serializer.save() # Write customer data to MongoDB. collection_name.insert_one(customer_serializer.data) response = { 'message': "Successfully uploaded a customer with id = %d" % customer_serializer.data.get('id'), 'customers': [customer_serializer.data], 'error': "" } return JsonResponse(response, status=status.HTTP_201_CREATED) else: error = { 'message': "Can not upload successfully!", 'customers': "[]", 'error': customer_serializer.errors } return JsonResponse(error, status=status.HTTP_400_BAD_REQUEST) except: exceptionError = { 'message': "Can not upload successfully!", 'customers': "[]", 'error': "Having an exception!" } return JsonResponse(exceptionError, status=status.HTTP_500_INTERNAL_SERVER_ERROR) elif request.method == 'DELETE': try: CustomerModel.objects.all().delete() # Delete customer data from MongoDB. collection_name.deleteMany({}) return HttpResponse(status=status.HTTP_204_NO_CONTENT) except: exceptionError = { 'message': "Can not delete successfully!", 'customers': "[]", 'error': "Having an exception!" } return JsonResponse(exceptionError, status=status.HTTP_500_INTERNAL_SERVER_ERROR) The POST method works fine and I can see the added … -
AttributeError: 'RelatedManager' object has no attribute '' reverse connection
I'm trying to implement reverse connection , but i get this error : 'admin':i.mobileinv_imei.invoice.seller.username, AttributeError: 'RelatedManager' object has no attribute 'invoice' this is my models.py class Imei(models.Model): mobile = models.ForeignKey(MobileCollection,on_delete=models.PROTECT) imei = models.CharField(max_length=15,unique=True) status= models.BooleanField(default=True) class ImeiInvoice(models.Model): item = models.ForeignKey(Imei,on_delete=models.PROTECT,related_name='mobileinv_imei') invoice = models.ForeignKey(CustomerInvoice,on_delete=models.CASCADE,related_name='invoice') price = models.DecimalField(max_digits=20,decimal_places=3) class CustomerInvoice(models.Model): seller = models.ForeignKey(User,on_delete=models.PROTECT) customer = models.CharField(max_length=50) mobiles = models.ManyToManyField(Imei,through='ImeiInvoice') im trying to return seller name from Imei model, here is my views.py def imei_sold_lists(request): imeis = Imei.objects.filter(status=False) lists = [] for i in imeis: imei = { 'admin':i.mobileinv_imei.invoice.seller.username, 'customer':i.mobileinv_imei.invoice.customer, 'imei':i.imei, 'price':i.mobileinv_imei.price } lists.append(imei) return JsonResponse({'data':lists}) is there something i've missed please? or should i change something please? Thank you for helping .. -
PostgreSQL delete record from two joined tables based on conditions
In my django project, with a PostgreSQL database connected i create these two models: class Results(models.Model): device = models.ForeignKey(Device, null=True, on_delete=models.SET_NULL) proj_code = models.CharField(max_length=400) res_key = models.SlugField(max_length=80, verbose_name="Message unique key", primary_key=True, unique=True) read_date = models.DateTimeField(verbose_name="Datetime of vals readings") unit = models.ForeignKey(ModbusDevice, null=True, on_delete=models.SET_NULL) class VarsResults(models.Model): id = models.AutoField(primary_key=True) key_res = models.ForeignKey(Results, related_name="keyres", on_delete=models.CASCADE) var_id = models.ForeignKey(ModbusVariable, null=True, on_delete=models.SET_NULL) var_val = models.CharField(max_length=400, blank=True) var_val_conv = models.CharField(max_length=100, blank=True, null=True) base_byte_order = models.CharField(max_length=15) var_hash = models.CharField(max_length=400) has_error = models.BooleanField(default=False) so VarsResults have a Foreignkey to Results, i would delete some records in both table starting from a condition based on Results, for example DELETE RECORDS FROM RESULTS IF RESULTS read_date < VALUE i would to automatically also delete all related records in VarsResults table. Is there a method in django ORM or directly using SQL for achieve this? So many thanks in advance -
How can I send a sms in Django?
I encountered a problem when trying to send sms using the SMSC service in Django project. My Celery task for sending email and sms: def order_created_retail(order_id): # Task to send an email when an order is successfully created order = OrderRetail.objects.get(id=order_id) subject = 'Order №{}.'.format(order_id) message_mail = 'Hello, {}! You have successfully placed an order{}. Manager will contact you shortly'.format(order.first_name, order.id) message_sms = 'Your order №{} is accepted! Wait for operator call' mail_sent = send_mail( subject, message_mail, 'email@email.com', [order.email] ) smsc = SMSC() sms_sent = smsc.send_sms( [order.phone], str(message_sms) ) return mail_sent, sms_sent Email sends correctly, but for sms I get that error: Task orders.tasks.order_created_retail[f05458b1-65e8-493b-9069-fbaa55083e7a] raised unexpected: TypeError('quote_from_bytes() expected bytes') function from SMSC library: def send_sms(self, phones, message, translit=0, time="", id=0, format=0, sender=False, query=""): formats = ["flash=1", "push=1", "hlr=1", "bin=1", "bin=2", "ping=1", "mms=1", "mail=1", "call=1", "viber=1", "soc=1"] m = self._smsc_send_cmd("send", "cost=3&phones=" + quote(phones) + "&mes=" + quote(message) + \ "&translit=" + str(translit) + "&id=" + str(id) + ifs(format > 0, "&" + formats[format-1], "") + \ ifs(sender == False, "", "&sender=" + quote(str(sender))) + \ ifs(time, "&time=" + quote(time), "") + ifs(query, "&" + query, "")) # (id, cnt, cost, balance) или (id, -error) if SMSC_DEBUG: if m[1] > "0": print("Сообщение … -
Performing DELETE call in DRF using axios returns 301
I'm struggling with calling delete on my drf api using axios. Constantly returns 301... I'm having one class based view containing create/list/delete methods. What might be wrong here? axios call: async delete_qr(id){ api.delete("tickets/qr/delete/"+String(id), {headers:{Authorization:'JWT '+this.$store.state.jwt}, data:{pk:id}}) .then(response => { console.log(response.data) this.tickets = response.data }) .catch(error => { console.log(error) }) views.py class TicketApi(CreateAPIView, ModelViewSet): permission_classes = ( permissions.IsAdminUser, permissions.IsAuthenticated, ) authentication_classes = (JSONWebTokenAuthentication,) serializer_class = TicketSerializer queryset = Tickets.objects.all() def destroy(self, request, pk): ticket = self.get_object(pk) self.perform_destroy(ticket) return Response({"info":f"ticket with id {pk} has been deleted"}, status=status.HTTP_200_OK) urls.py router = routers.DefaultRouter() router.register("qr/create", TicketApi, basename="qr_create") router.register("qr/list", TicketApi, basename="qr_list") router.register("qr/delete", TicketApi, basename="qr_delete") -
Django query number of occurences of a character in CharField
I have a CharField who contains paths, like: zero/one/two/three , or root/usr/et_cetera The number of separators (here /) give us the depth of the 'node' in the path, so on the previous example, three has a depth of 3. In python, I could write 'zero/one/two'.count('/'), but I wonder how to do it in a Django query. What I search is something like following: # Hypothetical code, does not work Model.object.annotate(depth=CountChr('path', V('/'))).filter(depth=2) I can't find a function who does that in the django documentation. -
Cannot Iterate through the array list in Django
I'm iterating through all the records from database but only one the first row is reflecting in the output. The database data which are list of tuples [(('HR749', datetime.datetime(2021, 11, 5, 20, 0, 17), 'Web', 'Referrals ', 'Draft', 'Bus', 'India', 'satish', 10902, 'Openings', datetime.date(2021, 11, 10),('HR855', datetime.datetime(2021, 11, 5, 20, 11, 41), 'Web', 'Referrals ', 'Draft', 'BusS', 'India', 'mah', 83837, ' referral', datetime.date(2021, 11, 10)), ('HR929', datetime.datetime(2021, 11, 5, 20, 22, 58), 'Web', 'Referrals ', 'Draft', 'BusS', 'India', 'ritika', 6124, 'Unable to submit', datetime.date(2021, 11, 10))] Here, what I have tried I know its simple but I don't know why I couldn't able to get all the records from the database views.py: @api_view(['GET', 'POST']) def ClaimReferenceView(request,userid): try: userid = Tblclaimreference.objects.filter(userid=userid) except Tblclaimreference.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': userID = request.data.get(userid) print(userID) cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetClaims] @UserId= %s',('10',)) result_set = cursor.fetchall() print(type(result_set)) print(result_set) for row in result_set: Number= row[0] Opened = row[1] Contacttype = row[2] Category1 = row[3] State = row[4] Assignmentgroup = row[5] Country_Location = row[6] Openedfor = row[7] Employeenumber = row[8] Shortdescription = row[9] AllocatedDate = row[10] return Response({"Number":Number,"Opened":Opened, "Contacttype": Contacttype, "Category1":Category1, "State":State, "Assignmentgroup":Assignmentgroup, "Country_Location": Country_Location, "Openedfor":Openedfor, "Employeenumber":Employeenumber, "Shortdescription": Shortdescription, "AllocatedDate":AllocatedDate}, status=status.HTTP_200_OK) -
NOT NULL constraint failed:orders_order.user_id
I am new to django and i am building an ecommerce website. When i try to make a new order in my website i got this error: NOT NULL constraint failed:orders_order.user_id each user can have multiple orders and i want to show the orders in the users profile but i am having problem with placing orders models.py class Order(models.Model): user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) address = models.CharField(max_length=250) postal_code = models.CharField(max_length=11) city = models.CharField(max_length=100) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) paid = models.BooleanField(default=False) class Meta: ordering = ('-created',) def __str__(self): return f'Order {self.id}' def get_total_cost(self): return sum(item.get_cost() for item in self.items.all()) class OrderItem(models.Model): order = models.ForeignKey(Order, related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, related_name='order_items', on_delete=models.CASCADE) price = models.DecimalField(max_digits=10, decimal_places=2) quantity = models.PositiveIntegerField(default=1) def __str__(self): return str(self.id) def get_cost(self): return self.price * self.quantity forms.py class OrderCreateForm(forms.ModelForm): class Meta: model = Order fields = ['address', 'postal_code', 'city'] views.py def order_create(request): cart = Cart(request) if request.method == 'POST': user = request.user form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in cart: OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity']) context = { 'order': order, } # clear the cart cart.clear() return render(request, 'order/created.html', context) else: form = OrderCreateForm() context = {'cart': cart, 'form': form, } return render(request, 'order/create.html', context) … -
How to use FCM pkg on Django?
I'm using the fcm_django package to send notifications API to Firebase but I have some confusion about those two concepts on Firebase like so: (registeration_id and device_id) https://fcm-django.readthedocs.io/en/latest/#setup I placed the "server_key" of Firebase to registration_id but don't understand what does device_id means and what is the value I should put on it? after answering the above questions I tried to send notification from Django by the admin page on Django by creating registration_id which is "server_key" and defining the type which is a "web", but when I created this object I didn't see any message has been sent to Firebase cloud. Note:- I want to send notifications to only one device not many users. so, can anyone help me to achieve this mission succeeded? Thanks in advance -
How i can fetch fields from models and calculate some filed and pass them to my template?
my model.py class Main(models.Model): name= .... amount = models.PositiveIntegerField(default=40000) In my views: def mainf(request): listmain = models.Main.objects.all() for data in listmain: value = data.amount * 5 calculated_data = data_and_value context = {'main':calculated_data} return render(request,'main/main.html',context) How i can fetch fields from models and calculate some fileds and pass them(calculated_data) to my template?