Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Scrapyd Django: how to properly check when the crawl has finished
I’m asking for help with an issue I’m stuck with and I cannot figure out how to proceed. There are some similar questions but the answers are not what I’m looking for. Basically I wrote a spider with Django and Scrapy. I’m using Scrapyd to run a big number of spiders for various users. What I need to do is to check the status of a crawl in order to see if it is running or has finished. This is because I want to show the crawl analysis to the users (via an HTML button)only after a crawl has finished, and not before when it’s halfway through the process. Scrapyd has the listjobs endpoint which gives back the status for each crawl: {"status": "ok", "pending": [{"id": "78391cc0fcaf11e1b0090800272a6d06", "spider": "spider1"}], "running": [{"id": "422e608f9f28cef127b3d5ef93fe9399", "spider": "spider2", "start_time": "2012-09-12 10:14:03.594664"}], "finished": [{"id": "2f16646cfcaf11e1b0090800272a6d06", "spider": "spider3", "start_time": "2012-09-12 10:14:03.594664", "end_time": "2012-09-12 10:24:03.594664"}]} The problem with this is that I need to check this until the status is “finished”, so that I can show the button. So I would need to call it every X seconds to check for the status. I also know there is close_spider method in Scrapy pipeline, but not sure if … -
When does Django / Mongo dereference a ReferenceField?
When does Django/ Mongo dereference a ReferenceField. Let’s say I do something like: class ModelA: rf=fields.ListField(fields.ReferenceField(ModelB)) class ModelB: pass A=[ x for x in ModelA.rf] B=ModelB.objects.filter(id__in=[ x.id for x in ModelA.rf]) Would there be a difference in number of DB calls in case of A and B -
Ajax: How to send FormData inside of json object
To give you a better understanding consider my ajax request: $.ajax({ url: '{% url "validate-upload-single" %}', type: "POST", data: JSON.stringify({ 'mainForm': Myform, 'currentForm': 1, }), dataType: 'json', // response type Where: var Myform = new FormData( $(this)[0] ); The problem is that when i send the request, i get back an empty 'dict' on the server side. Im using Django as my backend DJANGO VIEW: print('SORTING THE POST REQUEST') body = request.body.decode('utf-8') serialized = loads(body) print(f'POST: {request.POST}') print(f'Body: {body}') print(f'Serialized: {serialized}') RESULT: SORTING THE POST REQUEST POST: <QueryDict: {'{"mainForm":{},"currentForm":1}': ['']}> Body: {"mainForm":{},"currentForm":1} Serialized: {'mainForm': {}, 'currentForm': 1} I've tried $("form").serializeArray() but this only return text data, files seem to be missing -
Save Django's tests results to real database
Triyng to run Selenium tests in Django. I need to get data from the database, update it and save it to the real database. What will be the best way to achive that? -
Getting the Network Console Response object in django rest framework api using Reactjs
Hello Guys Iam making an app in reactjs that will allow users to upload csv and xlsx files and give them alerts if the files fail to upload so am trying to get the object from the response in network console when you inspect the page and to be able to display the message on the js page for users so that they wont have to right click to inspect the page, click network and response to see the error or succes messages what I want them to do is if a file fails to upload that message object should be presented on the page. Here is a sample code: import React from "react"; import PropTypes from "prop-types"; import axios from 'axios' class Uploaddatastore extends React.Component { constructor(props) { super(props); this.state = { UploadNotification: [] } } componentDidMount(){ let notificationComponent = this; axios.get("http://127.0.0:8000/uploads/file_upload/") .then(function (response) { console.log(response); console.log(response.data); notificationComponent.setState({ UploadNotification: response.data.items }); }) .catch(function (error) { console.log(error); }); } render() { let renderItems; if (this.state.UploadNotification.length) { renderItems = this.state.UploadNotification.map(function(item, i) { return <li key={i}>{item.title}</li> }); } return ( <div className="App"> <div className="form-group mt-3"> <label className="mr-2">Upload your File:</label> <input type="file" name="title" accept=".xlsx , .csv" multiple onChange={(e) => this.handleFile(e)} filetype={'.csv,.xlsx'} /> </div> … -
Django: How to make many filters on the same related field?
I have a Django model called Format, that has some fields, and another model called DepartmentFormat that looks like this class DepartmentFormat(models.Model): department = models.ForeignKey(Department, on_delete=models.CASCADE) format = models.ForeignKey(Format, on_delete=models.CASCADE, related_name='format_dptfmt') status = models.ForeignKey(FormatStatus, on_delete=models.CASCADE, null=True, default=None) In my view to display the formats, I have some filters, like this: class FormatFilter(FilterUserMixin): # SOME OTHER FILTERS class Meta: model = Format fields = ("business_type", "rfc", "economic_sector", "cellphone", "format_dptfmt__status__status") However, the same Format can have multiple DepartmentFormat objects related to it, because they can have the same Format, but different Department. For example, this is a possible case: A format has two DepartmentFormat objects related to it. One of those has "Ecology department" as its department, and another has "Public works department" as its department. There exists a third Department, which has still no DepartmentFormat object related to it. So this same Format could have zero, one, two or three DepartmentFormat objects related to it, with each of the Department objects that exist. What I'm after, is having three filters, one for each of the departments. The first one, for instance, could filter only those Formats for which there is a related DepartmentFormat that happens to have "Ecology department", and the … -
How to get a SQL queryset in Django?
I am new to django, and now I am making a query to my models, the query is already made in mysql. How can I get the following SQL queryset in Django? Query made in mysql MySql SELECT `ae`.`id` AS `event_id`, `ae`.`startdatetime` AS `startdatetime`, `ae`.`enddatetime` AS `enddatetime`, `ae`.`active` AS `active`, `ae`.`logged_user` AS `logged_user`, `aa`.`id` AS `area_id`, `aa`.`area_name` AS `area_name`, `ad`.`id` AS `device_id`, `ad`.`device_name` AS `device_name`, `ad1`.`user_description` AS `digitaloutput_user_description`, `al`.`user_description` AS `lighstate_user_description`, CONCAT(`ad1`.`user_description`, ' - ', `al`.`user_description`) AS `do_lightstate_user_description`, `ad1`.`color` AS `color`, `ae`.`shift_startdatetime` AS `shift_startdatetime`, `ae`.`shift_enddatetime` AS `shift_enddatetime`, `ae`.`shift_name` AS `shift_name` FROM ((((`andon_event` `ae` JOIN `andon_lightstate` `al` ON ((`ae`.`lightstate_id_id` = `al`.`id`))) JOIN `andon_device` `ad` ON ((`ae`.`device_id_id` = `ad`.`id`))) JOIN `andon_area` `aa` ON ((`ae`.`area_id_id` = `aa`.`id`))) JOIN `andon_digitaloutput` `ad1` ON ((`al`.`do_id_id` = `ad1`.`id`))) These are my class models: MODELS Event Model: class event(models.Model): device_id = models.ForeignKey('device', on_delete=models.CASCADE, null=True) startdatetime = models.DateTimeField(auto_now=False, auto_now_add=False, null=False) enddatetime = models.DateTimeField(auto_now=False, auto_now_add=False, null=True) active = models.BooleanField(default=False) logged_user = models.CharField(max_length=100, null=True) shift_startdatetime = models.DateTimeField(auto_now=False, auto_now_add=False, null=True) shift_enddatetime = models.DateTimeField(auto_now=False, auto_now_add=False, null=True) shift_name = models.CharField(max_length=100, null=True) . . . Devie Model: class device(models.Model): device_name = models.CharField(max_length=50, unique=True, help_text='Station Name', validators=[validate_slug]) Area Model: class area(models.Model): area_name = models.CharField(max_length=100, unique=True, default='New Unnamed Area', help_text='Area Name') Digitaloutput Model: class digitaloutput(models.Model): user_description = … -
Django Rest Framework - Filter fields of nested relationships
I want to return a nested representation of Customer with Image objects, where a Customer can have many Images. Currently, the nested representation returns ALL images from the Image queryset for each Customer object as shown below. How can I show only related Image(s) under each Customer object instead? # 'images' field Currently returns all images rather than related images to the customer id. { 'id': 1, 'name': 'John Doe', 'images': [ {'id': 1, 'name': 'foo.jpg', 'customer': 1}, {'id': 2, 'name': 'bar.jpg', 'customer': 2}, {'id': 3, 'name': 'foobar.jpg', 'customer': 3}, ... ], } ... This is my current setup Example Models class Customer(models.Model): name = models.CharField() class Image(models.Model): name = models.CharField() customer = models.ForeignKey( Customer, on_delete=models.CASCADE) Example Serializers class CustomerSerializer(serializers.ModelSerializer): # My Customer nested relationship is expressed using ImageSerializer as a field images = ImageSerializer(many=True) class Meta: model = Customer fields = ('id', 'name', 'images') read_only_fields = ('id',) class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = '__all__' read_only_fields = ('id',) Please let me know if my question is unclear and I will update my question. Thank you. -
Celery asynchronous in django does not work
I am trying to create an asynchronous task using celery, but I am not achieving success. I have a task that sends emails: @shared_task() def send_email_example(email_id): ... I call it using the delay() method: class SomeModelExample: ... def example(self): ... send_email_example.delay(self.id) Locally, I run the celery and can use it. However, in my server, when I use the method that calls the function it takes more than 30 seconds and I receive a status code 502. I hope that my celery setup is ok, because my periodc tasks works. -
Is a mailto URL with slashes still valid?
I am using a subclassed Django URLField to perform some validation on clicked URLs. I added mailto as one of the supported URLValidator default_validators: class MyURLField(forms.URLField): default_validators = [ validators.URLValidator( schemes=['http', 'https', 'ftp', 'ftps', 'mailto'] ) ] class MyForm(forms.Form): url = MyURLField(required=True) form = MyForm({'url': 'mailto:test@example.com'}) if not form.is_valid(): raise Exception() clean_url = form.cleaned_data['url'] print(clean_url) # this prints 'mailto://test@example.com' Is a mailto URL still valid with the two extra protocol slashes? mailto:test@example.com versus mailto://test@example.com (what Django produces) -
Django Models compare 2 model and filter
i want to get the model details with corresponding another model my models.py class Device(models.Model): DeviceName = models.CharField(max_length=50, null=True, default=None, blank=True) Camera = models.ForeignKey(Camera, on_delete=models.CASCADE, db_column='CameraId') class Meta: db_table = "Device" class Camera(models.Model): CameraId = models.AutoField(primary_key=True, db_column='CameraId') CameraName = models.CharField(max_length=50) class Meta: db_table = "Camera" i want my camera details that is the camera details that not saved in Device foreign key (means the camera details that not used the foreign key for device) -
Form with bootstrap
I'm trying to make the create form look better but it just doesn't work. It shows fine but when I try to submit it doesn't do anything. I've already tried with different forms of one field, I think I can't make it work because this has file fields and foreign keys, etc. Why it doesn't work? forms.py class Lcreate(forms.ModelForm): class Meta: model = Auction fields = ('name', 'img', 'description', 'category', 'starting_bid') widgets = { 'description' : forms.Textarea(attrs={ 'rows': '5', 'cols': '90', 'maxlength': '500', }), 'name' : forms.Textarea(attrs={ 'rows': '1', 'cols': '100', 'maxlength': '30', }), } views.py @login_required(login_url="login") def create(request): if request.method == "POST": form = Lcreate(request.POST or None, request.FILES or None) if form.is_valid(): user = request.user starting_bid = form.cleaned_data["starting_bid"] description = form.cleaned_data["description"] name = form.cleaned_data["name"] img = form.cleaned_data["img"] category = form.cleaned_data["category"] listing = Auction(user=user, starting_bid=starting_bid, description=description, name=name, img=img, category=category) listing.save() return redirect('index') else: form = Lcreate() return render(request, "auctions/create.html", { "form": Lcreate, "categories": Category.objects.all() }) html <div class="space"></div> <div class="create-form"> <h1>Create Listing</h1> <form method="POST" enctype="multipart/form-data"> {%csrf_token%} <div class="form-group"> <label for="name">Title</label> <input autofocus class="form-control" id="name" type="text" name="name" placeholder="Title"> <div class="space"></div> <label for="img">Image</label> <input type="file" id="img" name="img" class="form-control-file"> <div class="space"></div> <label for="description">Description</label> <textarea class="form-control" name="description" id="description" rows="3" placeholder="description"></textarea> <div class="space"></div> <label for="category">Category</label> … -
django throwing ImproperlyConfigured error while importing data using 'django-import-export' library
I'm trying to import data into a model through django admin using dajngo-import-export library, though I'm facing "Improperly Configured" error. This is the error message: ImproperlyConfigured at /admin/pages/quote/import/ No exception message supplied Request Method: POST Request URL: http://127.0.0.1:8000/admin/pages/quote/import/ Django Version: 3.0 Exception Type: ImproperlyConfigured Exception Location: C:\Users\Dell\.virtualenvs\read_bus-UfMQ3ck8\lib\site-packages\import_export\resources.py in import_data, line 737 Python Executable: C:\Users\Dell\.virtualenvs\read_bus-UfMQ3ck8\Scripts\python.exe Python Version: 3.7.3 Python Path: ['C:\\Users\\Dell\\Downloads\\read_bus', 'C:\\Users\\Dell\\.virtualenvs\\read_bus-UfMQ3ck8\\Scripts\\python37.zip', 'C:\\Users\\Dell\\.virtualenvs\\read_bus-UfMQ3ck8\\DLLs', 'C:\\Users\\Dell\\.virtualenvs\\read_bus-UfMQ3ck8\\lib', 'C:\\Users\\Dell\\.virtualenvs\\read_bus-UfMQ3ck8\\Scripts', 'c:\\users\\dell\\anaconda3\\Lib', 'c:\\users\\dell\\anaconda3\\DLLs', 'C:\\Users\\Dell\\.virtualenvs\\read_bus-UfMQ3ck8', 'C:\\Users\\Dell\\.virtualenvs\\read_bus-UfMQ3ck8\\lib\\site-packages', 'C:\\Users\\Dell\\Downloads\\read_bus', 'C:\\Users\\Dell\\.virtualenvs\\read_bus-UfMQ3ck8\\lib\\site-packages\\odf', 'C:\\Users\\Dell\\.virtualenvs\\read_bus-UfMQ3ck8\\lib\\site-packages\\odf', 'C:\\Users\\Dell\\.virtualenvs\\read_bus-UfMQ3ck8\\lib\\site-packages\\odf', 'C:\\Users\\Dell\\.virtualenvs\\read_bus-UfMQ3ck8\\lib\\site-packages\\odf', 'C:\\Users\\Dell\\.virtualenvs\\read_bus-UfMQ3ck8\\lib\\site-packages\\odf', 'C:\\Users\\Dell\\.virtualenvs\\read_bus-UfMQ3ck8\\lib\\site-packages\\odf', 'C:\\Users\\Dell\\.virtualenvs\\read_bus-UfMQ3ck8\\lib\\site-packages\\odf',] I'm following the documentation as mentioned here. This is the admin.py file: class QuoteResource(resources.ModelResource): class Meta: model =Quote import_id_fields=('quote',) fields = ('quote','book','author',) class QuoteAdmin(ImportExportModelAdmin): list_display=('quote','book','author') resource_class =QuoteResource admin.site.register(Quote,QuoteAdmin) I've tried with and without 'QuoteResource', without success. I'm successfully able to export the data from admin. But facing challenge during import. Snip of admin during import: Following is one of the various ways in which I tried to import data: Does it has somthing to do with the django settings or the csv data format? Let me if you need any more information. -
Will migrate zero save my migrate --fake mishap?
I have Django webapplication running on Heroku with Heroku Postgres. A few days ago I made a few changes to an app's models, adding and then removing unique=True to some model fields (among other things, just messing around a bit) and making some migrations. This surely broke something, and unfortunately I didn't discover this until a few days later, after I had made a lot of additional migrations in my local db. The only way I was able to fix it was with a: python manage.py migrate --fake This worked out OK on my local/dev postgres, but in production it is still broken when I try to make migrations and migrate. When running migrate: django.db.utils.ProgrammingError: table "publicinteraction_smoothmessage_extra_software" does not exist Since it has been a few days, I don't know exactly which migration I faked or not, and the section in Django docs about "risk of manually having to correct --fake" was also seen too late... Will it help to run python manage.py migrate publicinteraction zero or will this result in my data getting lost? This is my first project in production with real users and encountering such issues is all new to a self-taught developer in Python and Django. … -
NoReverseMatch at /'blog' is not a registered namespace
I am trying to link two pages. Page files are home.html and pageOne.html. I am getting "NoReverseMatch at /'blog' is not a registered namespace". I am using django. When I first created the app, I named it artclBlog, I then created a templates folder and another folder within that one, this one I named blog. I think I should have kept these two names the same, this may have caused some confusion in my code. pic of error my views.py from django.shortcuts import render, get_object_or_404 from .models import Blog def home(request): blogs = Blog.objects.order_by('-date') return render(request, 'blog/home.html', {'blogs': blogs}) my urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings from artclBlog import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), path('<int:blog_id>/', views.PageOne, name='PageOne') ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) my models.py from django.db import models class Blog(models.Model): title = models.CharField(max_length=200, default='') summary = models.CharField(max_length=200, default='') pageOne = models.TextField(default='') pageTwo = models.TextField(default='') pageThree = models.TextField(default='') pageFour = models.TextField(default='') date = models.DateField(default='') def __str__(self): return self.title -
Django Forms Crispy- change, clear and currently fields do not appear
I am not Software Engineer, I hate programming , but I would like to know how to solve this problem. PLEASE When I try to change a model instance using a form, the fields/messages/text Currently, Change, Clear for a File or Image are not appearing What is the solution? models.py class Part(models.Model): ... image = models.FileField(upload_to='images/', blank=True) datasheet = models.FileField(upload_to='files/', blank=True) ... form.py class PartForm(forms.ModelForm): class Meta: model = Part exclude = ["owner"] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.attrs['autocomplete'] = 'off' self.helper.form_method = "POST" self.helper.layout = Layout( Row( ... ), 'description', 'detailed_description', Row( ... ), Row( .... ), Row( Column('image', css_class='form-group col-md-6 mb-0'), Column('datasheet', css_class='form-group col-md-6 mb-0'), css_class='form-row' ), Submit('submit', 'Submit') ) urls.py urlpatterns = [ path("<uuid:pk>/change-part/", add_or_change_part, name="manage_change_part"), ] views.py def add_or_change_part(request, pk=None): part = None if pk: part = get_object_or_404(Part, pk=pk) if request.method == 'POST': form = PartForm(request.POST, request.FILES, instance = part) if form.is_valid: form = form.save(commit=False) form.owner = request.user form.save() return redirect ('part_main') else: form = PartForm(instance=part) context = {"form": form} return render(request, 'part_form.html', context) part_form.html {% extends '_base.html' %} {% load static %} {% load crispy_forms_tags %} {% block title %} {% endblock title %} {% block page_header %} {% endblock page_header … -
Django doesn't recognize my custom update method in a serializer
i'm trying to patch an object in an app in Django Rest Framework But im getting the following error AssertionError at /requirements/material/12/ The .update() method does not support writable nested fields by default. Write an explicit .update() method for serializer requirement.serializers.MaterialRequirementDetailSerializer, or set read_only=True on nested serializer fields. The main problem here is that i already create an explicit update method. Here is my View.py where i make the patch request def patch(self, request, pk, format=None): requirement = models.MaterialRequirement.objects.get(pk=pk) serializer = serializers.MaterialRequirementDetailSerializer( requirement, data = request.data, partial = True ) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) and here is the serializer that i'm using class MaterialRequirementDetailSerializer(serializers.ModelSerializer): owner = UserListSerializer() construction_site = ConstructionSiteListSerializer() quotations = QuotationListSerializer( source='quotation_set', many=True, read_only=True ) items = RequirementItemSerializer( many=True ) state = serializers.CharField(source='get_state_display') type = serializers.CharField(source='get_type_display') delivery_time = serializers.CharField(source= 'get_delivery_time_display') class Meta: model = MaterialRequirement fields = ( 'id', 'code', 'state', 'type', 'deadline', 'description', 'observation', 'owner', 'construction_site', 'delivery_date', 'delivery_time', 'quotations', 'items' ) def update(self, instance, validated_data): requirement = super().update(instance, validated_data) items = self.context.get('items', None) if items: for item in items: if 'id' in item.keys(): requirement_item = RequirementItem.objects.get(pk=item['id']) if requirement_item: requirement_item.name = item['name'] requirement_item.description = item['description'] requirement_item.is_urgent = item['is_urgent'] requirement_item.quantity = item['quantity'] requirement_item.save() else: RequirementItem.objects.create(requirement … -
How do you access parent model fields in forms.py?
For context, I'm trying to create a form that allows users to upload info about their own custom Pokemon. Basically, they are creatures that you can catch, name, and level up. To draw a comparison, it is a similar concept to dogs; there are labradors, German Shepherds, huskies, etc. that would be variations of a base Dog model, but then each individual would have a name and other defining characteristics. I've created Pokemon and CustomPokemon models and imported the latter into my forms.py file. I'm trying to access some parent fields but am unable to: from django import forms from .models import CustomPokemon class PokemonForm(forms.ModelForm): class Meta: model = CustomPokemon fields = ['pokemon.poke_name', 'name', 'level'] The poke_name field is inherited from the base model while the other two fields belong to the CustomPokemon model. I'm getting this FieldError: Unknown field(s) (pokemon.poke_name) specified for CustomPokemon. The issue isn't resolved by using poke_name, so I'm curious how I can access the parent model's fields so they can be displayed in the form. -
Can I block users from accessing my API url?
I am making an Ecommerce website in DJango/Django-Rest-Framework. Now for update/delete/add to cart operations I am using AJAX so that JSON is sent dynamically to the API and data is serialized there. Now I have added permission that user can't see other people's API data but I don't want user to see his API data as well. I just want him to use the website while AJAX is done in the background. -
Django-Rest-Framework: Login Serializer Error
I am trying to implement the Login system myself, instead of relying on a third-party application. When I try to login, I get a 400 Bad Request Error saying, user with this email already exists, instead of the data, I want it to return. Login Serializer class UserLoginSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ("email", "password") extra_kwargs = {"password": {"write_only":True}} def validate(self, data): email = data["email"] password = data["password"] user = UserProfile.objects.get(email = email) if user: if not user.check_password(data["password"]): raise serializers.ValidationError("Incoreect Password") return data raise serializers.ValidationError("User Not Found") The LoginAPIView class UserLoginAPIView(APIView): def post(self, request): user = UserLoginSerializer(data = request.data) if user.is_valid(): return Response(user.data, status = status.HTTP_200_OK) return Response(user.errors, status = status.HTTP_400_BAD_REQUEST) -
Django MultiValueDictKeyError for upload file
There has a file upload page for upload file to a object by id in model. However, it shown MultiValueDictKeyError after submitted. I would appreciate if any help. models.py: class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) items = models.ManyToManyField(OrderItem) img_upload = models.FileField(upload_to='payment', null=True) forms.py: class Upload_File(forms.Form): class Meta: model = Order fields = ('img_upload') views.py: def upload_page(request, id): order = get_object_or_404(Order, id=id) form = Upload_File(request.POST or None, request.FILES or None) if request.method == 'POST': order.img_upload = request.FILES['image'] if form.is_valid(): form.save() messages.success(request, 'Succeed') return redirect('user_info') else: form = Upload_File() context = { 'form': form, } return render(request, 'upload.html', context) html: <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input class="form-group" type="file" name="image/> <button class="form-group" type="submit">Submit</button> </form> -
How to write details of parameters in django api documentation
I want to write details of parameters that are passed to an api in Django. I installed coreapi and added url for docs page: from rest_framework.documentation import include_docs_urls urlpatterns = [ path('admin/', admin.site.urls), path(r'docs/', include_docs_urls(title='API Documentation')) ] In views.py: class CreditAPI(APIView): serializer_class = CreditSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def post(self, request): """ This gets a post request with token and after authentication creates a credit for that user. """ CreditInfo.objects.get(user=request.user) try: currency = request.data.get('currency', None) credit = CreditInfo(currency=currency, user=request.user) credit.save() return Response(status=status.HTTP_201_CREATED) except: return Response(status=status.HTTP_400_BAD_REQUEST) So I have following document page: My question is how can I add details of parameters in a table in this page? -
How can i choose a different python version after set a virtual enviroment ? im on win10
i have 2 version of python installed on my win10 machine 3.6 and 38 depending on my project how to launch one rather than the other ? Do i need to choose before i set the vrtual enviroment ? basically i was wondering after setting my virtual enviroment, how to choose the one i want to use for the project ? any indication? id love to do like i do in choosing django version.. for example pip install django==2.1 , how can i do for choosing python version ? -
How to handle update_fields to work on django?
I've the following code: investor.is_phone_verified = True investor.phone = phone_number investor.save(update_fields=['is_phone_verified', 'phone']) To update a flag and a certain field for investor user. when I try to get that user again and run, it return false: investor.is_phone_verified False Any working way to handle updating fields in django? I also tried: User.objects.filter(pk=user.pk).update(is_phone_verified=True) but also didn't work! -
Deleting a value from many to many field in views.py in django website
I am working on a basic ecommerce django website . My product model has the following: size=models.ManyToManyField(Siz) and this is the size model: class Siz(models.Model): size=models.CharField(max_length=3,null=True,blank=True) desc=models.CharField(max_length=110,null=True,blank=True) I have added the sizes manually in the django administration. What I want is that Whenever a user orders something the value of the size of the product that he ordered automatically is deleted from the product sizes available. This is my orderitem model that has the field of the selected size. class OrderItem(models.Model): product=models.ForeignKey(Product,on_delete=models.SET_NULL,null=True) order=models.ForeignKey(Order,on_delete=models.SET_NULL,null=True,) size=models.ForeignKey(Siz,on_delete=models.SET_NULL,null=True) and this is my views that checks when the order (payment for the order) is completed or not. @csrf_exempt def handlerequest(request, id): order=Order.objects.get(id=id) items=order.orderitem_set.all() form = request.POST verify = Checksum.verify_checksum(response_dict, MERCHANT_KEY, checksum) if verify: if response_dict['RESPCODE'] == '01': order.complete=True order.save() else: print(response_dict['RESPMSG']) order.delete() return render(request, 'handlerequest.html', {'response': response_dict,'order':order}) When the order is completed the order.complete is set to true.At that Time I want to deleted the ordered size.Please help me with a way. Thanks