Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-elasticsearch-dsl Mapping for completion suggest field not working
This problem has been driving me crazy for days with not solution. I create a document as follows from my django model. from django_elasticsearch_dsl import fields @registry.register_document class QuestionDocument(Document): complete = fields.CompletionField(attr='title') class Index: name = 'questions' class Django: model = QuestionModel fields = ['text', 'title'] Now i want to perform a completion query like this: matched_questions = list(QuestionDocument.search().suggest("suggestions", word, completion={'field': 'complete'}).execute()) But i keep getting the following error: elasticsearch.exceptions.RequestError: RequestError(400, 'search_phase_execution_exception', 'Field [complete] is not a completion suggest field') I think the problem is that The mapping for this field is not created correctly, but i don't know how to fix it. Can anybody help with this it is literally driving me crazy. -
Why can i use requests in Python shell but i get the error no module found in Django?
I get the error module not found when trying to import requests in Django. I cannot get python module requests to work in Django. I have installed the module using pip in python and can import in the python terminal. ModuleNotFoundError: No module named 'requests' if I run the commands in python shell: import requests test = requests.get(url="http://192.168.9.186:2480/connect/test") i get a htto 204 response but in django I just get the module error -
Django DATE_FORMAT weekday name
I want to format date object in Django. Specifically, I want to use DATE_FORMAT in settings.py. Using Django Documentation, I set it as: DATE_FORMAT = 'l, m F Y'. Lowercase l means weekday name. In the template I use {{ value|date:"DATE_FORMAT" }}, but it never renders the weekday name. If I do the: {{ value|date:"l, m F Y" }}, I get the results expected. Are there any limitations which built-in date filters are allowed in settings.py? Thank you! -
How to paginate bootstrap cards with django
I am getting my query results based on user selection and showing them on bootstrap cards in django. I am using django Paginator to display at max 6 results per page (currently set to 1 for testing). The problem is my Paginator is showing all the results on all the pagination pages. Could someone please help me?? View: def results(request): results = [] query_city = request.GET.get('city') print(query_city) all_records = hotel.objects.all() for states in all_records: if states.confirm_approval and states.space_state == query_city: print(states) results.append(states) paginator = Paginator(results,1) page = request.GET.get('page') try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: items = paginator.page(paginator.num_pages) index = items.number - 1 max_index = len(paginator.page_range) start_index = index - 5 if index >= 5 else 0 end_index = index + 5 if index <= max_index - 5 else max_index page_range = paginator.page_range[start_index:end_index] context = { 'results':results, 'items':items, 'page_range':page_range, } return render(request, 'results/results.html', context) Html Template: % for result in results %} {% if forloop.counter0|divisibleby:3 %} <div class="row"> {% endif %} <div class="col"> <div class="card-deck" id="cardholder"> <div class="card" style="max-width: 20rem;"> <img class="card-img-top" src="{% static 'mainpage/img/bg/books.jpg' %}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{ result.hotel_name }}</h5> </div> <div class="card-footer"> <a href="#" class="btn btn-primary">Show more</a> </div> </div> </div> … -
How do you call a javaScript function inside a Django template?
I want to call the javaScript function defined inside the same template in Django. How can I do it? {% extends 'base.html' %} {% block content %} {% if error %} showAlert() {% endif %} <script> function showAlert() {alert ("Please select at least one option");}</script> {% endblock %} I want to call showAlert() if there is error present. I have handled the error in the view. I do not a method about how to call the function here? It is showing the function name. -
django-rest-auth "userprofile with this email address already exists." in login
I'm using django rest auth for auth in my rest api. I use custom user model with no username field. So, I've to use custom login serializer. But when I log in, django rest auth says "userprofile with this email address already exists.". How to solve this problem? my settings: REST_USE_JWT = True REST_AUTH_SERIALIZERS = { 'LOGIN_SERIALIZER': 'accounts.api.serializers.RestAuthLoginSerializer', 'REGISTER_SERIALIZER': 'accounts.api.serializers.RestAuthRegisterSerializer', } ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USER_MODEL_USERNAME_FIELD = 'email' ACCOUNT_USERNAME_REQUIRED = False serializers.py from rest_framework import serializers from accounts.models import UserProfile class RestAuthLoginSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('email', 'password') class RestAuthRegisterSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('email', 'password', 'first_name', 'last_name', 'business_name', 'is_business_account') models.py class UserProfile(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True, null=True) last_name = models.CharField(_('last name'), max_length=30, blank=True, null=True) avatar = models.ImageField(upload_to='avatars/', null=True, blank=True) # business profile related data business_name = models.CharField(_('business name'), max_length=30, blank=True, null=True) business_phone = models.CharField(_('business phone'), max_length=20, blank=True, null=True) is_business_account = models.BooleanField(verbose_name=_("is business account"), default=False) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) is_active = models.BooleanField(_('active'), default=True) is_admin = models.BooleanField(_('staff status'), default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] -
Django: One function, two class-based views
I am currently struggling to find a better solution for get_survey_state(self, context). It is in both CBVs and I think there is a better solution than mine. Can you advise me on that? views.py class SurveyExpectations(AdminPermissionRequiredMixin, TemplateView): template_name = 'admin/surveys/expectations.html' def get_survey_state(self, context): survey = self.request.event.surveys.active_pre_event().first() answers = Answer.objects.filter(question__survey=survey).exists() context['survey_is_active'] = survey context['answers_exist'] = answers def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) self.get_survey_state(context) context['questions_and_answers'] = self.request.event.surveys.get_results( settings.SURVEY_PRE_EVENT ) return context class SurveyFeedback(AdminPermissionRequiredMixin, TemplateView): template_name = 'admin/surveys/feedback.html' def get_net_promoter_score(self) -> float: [...] return netpromoterscore(scores) def get_average_age(self) -> int: [...] return int(answers['avg']) if answers['avg'] else None def get_survey_state(self, context): survey = self.request.event.surveys.active_post_event().first() answers = Answer.objects.filter(question__survey=survey).exists() context['survey_is_active'] = survey context['answers_exist'] = answers def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) self.get_survey_state(context) context['questions_and_answers'] = self.request.event.surveys.get_results( settings.SURVEY_POST_EVENT ) context['netpromoterscore'] = self.get_net_promoter_score() context['average_age'] = self.get_average_age() return context models.py class SurveyQuerySet(models.QuerySet): def active_pre_event(self): return self.filter(is_active=True, template=settings.SURVEY_PRE_EVENT) def active_post_event(self): return self.filter(is_active=True, template=settings.SURVEY_POST_EVENT) def get_results(self, template): return ( self.get(template=template) .questions.exclude(focus=QuestionFocus.EMAIL) .all() .prefetch_related('answers') ) class Survey(TimeStampedModel): id = models.UUIDField([...]) is_active = models.BooleanField([...]) template = models.CharField([...]) objects = SurveyQuerySet.as_manager() -
Serializers - one to many relation with user limit input
I have a problem with drf. I have device serializer: from rest_framework import serializers from smarthome.models import Device class DeviceSerializer(serializers.Serializer): id = serializers.ReadOnlyField() name = serializers.CharField(max_length=80) address = serializers.CharField(max_length=17) def create(self, validated_data): return Device.objects.create(**validated_data) def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.address = validated_data.get('address', instance.address) instance.save() return instance Also, i have result serializer: from rest_framework import serializers from smarthome.models import Result from smarthome.models import Device class ResultSerializer(serializers.Serializer): temperature = serializers.CharField(max_length=80) moisture = serializers.CharField(max_length=80) light = serializers.CharField(max_length=80) conductivity = serializers.CharField(max_length=80) battery = serializers.CharField(max_length=80) date = serializers.ReadOnlyField() device = serializers.PrimaryKeyRelatedField(queryset=Device.objects.all()) def create(self, validated_data): print(validated_data) return Result.objects.create(**validated_data) I dont know how to add device results to device serializer. Also i want to have possibility to use limit send from user to limit number of results in response. There is my models: class Device(models.Model): name = models.CharField(max_length=80) address = models.CharField(max_length=17) class Result(models.Model): temperature = models.CharField(max_length=80) moisture = models.CharField(max_length=80) light = models.CharField(max_length=80) conductivity = models.CharField(max_length=80) battery = models.CharField(max_length=80) date = models.DateTimeField(auto_now_add=True) device = models.ForeignKey('Device', related_name='statuses', on_delete=models.CASCADE) Now, in response i got: { "id": 1, "name": "name", "address": "c4:7c:8d:6a:fb:27" } i want something like this: { "id": 1, "name": "name", "address": "c4:7c:8d:6a:fb:27", "results": { { "temperature": "21.5", "moisture": "61", ... }, { ... } } … -
QuerySet is empty when try to get User from multiple databases
I have a project with multiple databases. I'm trying to fetch all users from one of databases like this: users = User.objects.using('mydb').all() or this: users = User.objects.db_manager('mydb').all() but get an empty query list instead. <QuerySet [<User: >]> I've test this with some other models but they are working grate. Also when I've get the count of my records, return the correct number of records. Am I doing wrong? -
How to correclty setup Django Rest Framework social login and register, alongside local auth with jwt
I have to create API endpoints for user login and registration with facebook, twitter and local auth. I also want to connect social accounts with local one. Have used django-rest-auth and different packages and most of them are garbage. For example, django-rest-auth has issues with custom login serializers etc. How should it be done without writing messy code and without use of "bugfull" packages? -
Problem Using Bootstrap Navbar With For Loop In Template
Now I am trying to create a navbar for each intern profile in my website. To do that I used for loop and tried to create profiles as dynamically. The main issue is when clicking on tabs, every tab opens first models instances. As you understand only first model tabs work correctly I have tried to change href property of tabs but It does not work <!--Code part for calling tabs --> {% for intern in all_interns %} ....some part of codes before... <ul class="nav nav-tabs" id="myTab" role="tablist"> <li class="nav-item"> <a class="nav-link active" style="margin-bottom: 5px" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-controls="home" aria-selected="true" >Kişisel Bilgiler</a> </li> <li class="nav-item"> <a class="nav-link" id="profile-tab" data-toggle="tab" href="#profile" role="tab" aria-controls="profile" aria-selected="false">İş Bilgileri</a> </li> ...some part of codes after... {% endfor %} <!--Code part for each tabs --> <div class="col-md-8"> <div class="tab-content profile-tab" id="myTabContent"> <div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab"> "<div class="row"> <div class="col-md-6"> <label>Kullanıcı Adı</label> </div> <div class="col-md-6"> <p>{{ intern.user.username }}</p> </div> </div> <div class="row"> <div class="col-md-6"> <label>Şehir</label> </div> <div class="col-md-6"> <p>{{ intern.user.city }}</p> </div> </div> <div class="row"> <div class="col-md-6"> <label>Üniversite</label> </div> <div class="col-md-6"> <p>{{ intern.university }}</p> </div> </div> <div class="row"> <div class="col-md-6"> <label>Cinsiyet</label> </div> <div class="col-md-6"> {% if intern.user.gender == "Male" %} <p>Erkek</p> {% … -
How to Send Single request using ajax inside a loop
I create a simple mailer for our updates into client emails, But how can I send the data one by one and process each data on server side html: <p class="response"></p> <form id="send_updates"> {% csrf_token %} <textarea name="mail-list" class="mails" id="mails"></textarea> <button type="submit"> start sends </button> </form> javascript: let mails = $('#mails').val().split('\n'); for(let i = 0; i <= cc.length; i++){ $.ajax({ cache: false, type: 'post', url: "{% url 'send_mail' %}", data: {'email': mails[i]}, async: true, beforeSend:function(xhr, settings){ xhr.setRequestHeader("X-CSRFToken", "{{ csrf_token }}"); }; success: function(data){ if (data.success) == true{ $('.response').append(mails[i] + ' sent!') }else{ $('.response').append(mails[i] + ' not sent!') }; } }); BUT! It Sends All Request without waiting if it Success or Not! -
ValueError: save() prohibited to prevent data loss due to unsaved related object form - Create model with form obj as fk
I try to do the following class CaseCreateView(BSModalCreateView): template_name = 'orders/create_case_modal.html' form_class = NewCaseModal success_message = 'Success: Case was created.' success_url = reverse_lazy('scan_to_cart') def form_valid(self, form): case_num = random_string_generator() obj = form.save(commit=False) obj.user = self.request.user obj.case_number = case_num mess_obj = MessageEntry.objects.create(user=obj.user, message_fk=obj, mess_obj=obj.initial_memo) return super(CaseCreateView, self).form_valid(form) Which gives me the following error. ValueError: save() prohibited to prevent data loss due to unsaved related object 'message_fk'. This is a bootstrap_modal_forms window where I save a form. I want to create an object with a FK field (message_fk) hooked to the form obj. I can't save() the obj before assign it to the message_fk, because in that case the form saves twice. (don't know why) I never worked with class based views before and can't find a way to do this properly. -
How to prevent creating new object for existing ones when editing in inlineformset?
While editing a record in inline formset, after the submission new objects is created for existing ones also(duplicates). How to prevent that? I deleted the all objects in the model and reinserted it after checking is_valid(). Everything works fine but media files is not getting saved. views.py def edit_frm(request,id): ob = DynamicMain.objects.get(id=id) if request.method == 'POST': formsety = DocumentsUploadFormset(request.POST,request.FILES, prefix='formsety') formsetz = DocumentsDownloadFormset(request.POST,request.FILES, prefix='formsetz') if formsety.is_valid() and formsetz.is_valid(): del_up_ob = DocumentsUpload.objects.filter(title=ob).delete() #delete all objects del_dwn_ob = DocumentsDownload.objects.filter(title=ob).delete() for i in formsety: name = i.cleaned_data.get('name') mandatory = i.cleaned_data.get('mandatory') types_doc = i.cleaned_data.get('types_doc') location = i.cleaned_data.get('location') DocumentsUpload( title=ob, name=name, mandatory=mandatory, types_doc=types_doc, location=location, ).save() for i in formsetz: name = i.cleaned_data.get('name') mandatory = i.cleaned_data.get('mandatory') types_doc = i.cleaned_data.get('types_doc') location = i.cleaned_data.get('location') DocumentsDownload( title=ob, name=name, mandatory=mandatory, types_doc=types_doc, location=location, ).save() return redirect('app-admin:home') uploadformset = inlineformset_factory(DynamicMain, DocumentsUpload,extra=0,fields=('name','mandatory')) downloadformset = inlineformset_factory(DynamicMain, DocumentsDownload,extra=0, fields=('name','mandatory','types_doc')) formsety = uploadformset(prefix='formsety',instance=ob) formsetz = downloadformset(prefix='formsetz',instance=ob) context = { 'formsety' : formsety, 'formsetz' : formsetz, } return render(request,'app/edit_form.html', context) edit_form.html <h3>Upload</h3> <br> <div class="content formElements add_item_container six formsety hide_add_button"> <table cellpadding="0" cellspacing="0" class="table"> <tr> <th>Name</th> <th>Mandatory</th> </tr> {% for f in formsety.forms %} <tr class="form_up"> <td> <span class="p5name1"> {{ f.name }} </span> </td> <td> <span class="p5name1"> {{ f.mandatory }} </span> </td> <td>{% if f.instance.pk %}{{ f.DELETE … -
Django server and android not communicating correctly
Django Server and Android are not communicating correctly. In the test code, the onMassage method executes correctly when the websocket.send () method is executed. But if you change the url, after onOpen () is executed, it goes directly to onClose () without going through onMassage (). import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.WebSocket; import okhttp3.WebSocketListener; import okhttp3.logging.HttpLoggingInterceptor; import okio.ByteString; public class MainActivity extends AppCompatActivity { private Button start; private TextView output; private OkHttpClient client; private final class EchoWebSocketListener extends WebSocketListener { private static final int NORMAL_CLOSURE_STATUS = 1000; @Override public void onOpen(WebSocket webSocket, Response response) { webSocket.send("Hello, it's SSaurel !"); webSocket.send("What's up ?"); webSocket.send(ByteString.decodeHex("deadbeef")); webSocket.close(NORMAL_CLOSURE_STATUS, "Goodbye !"); } @Override public void onMessage(WebSocket webSocket, String text) { Log.e("asd", "on message"); output("Receiving : " + text); } @Override public void onMessage(WebSocket webSocket, ByteString bytes) { Log.e("asd", "on message"); output("Receiving bytes : " + bytes.hex()); } @Override public void onClosing(WebSocket webSocket, int code, String reason) { Log.e("asd", "on closing"); webSocket.close(NORMAL_CLOSURE_STATUS, null); output("Closing : " + code + " / " + reason); } @Override public void onFailure(WebSocket webSocket, Throwable t, Response response) { Log.e("asd", "on fail"); output("Error : " + … -
Django: presave signal to get file extension in Model
In Django, for file field, its possible to use callable for example user_directory_path in the code below. def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user.id, filename) class MyModel(models.Model): upload = models.FileField(upload_to=user_directory_path) extension = models.CharField(max_length=100, null=False, blank=False, default=get_filename_ext) However, for the extension field I want to use the get_filename_ext function so that extension of the file gets saved. def get_filename_ext(filepath): base_name = os.path.basename(filepath) name, ext = os.path.splitext(base_name) return name, ext Is there something similar in Django model? Or do I have to do this in Django view? -
How to pass selected value from one form to another without storing
I'm trying to send selected value from one form to another, then take that value as an int and use in a loop VIEW: def Base(request, *args, **kwargs): template_name = 'Base.html' odd = [1, 3, 5, 7, 9] form = Base_form(request.POST) if request.method == 'POST': if form.is_valid(): no_of = request.POST.get('odd') return HttpResponseRedirect("loopthru.html") return render(request, template_name, {'odd': odd}) def loopthru(request, *args, **kwargs): template_name = 'loopthru.html' print(request.POST.get('odd')) form = P2_NexusLeafPair_form(request.POST or None) ... How to pass the value from one form to another and then ran the function loopthru automatic and render the html data. -
Error while accessing request.session['key'] inside forms. [using CheckboxSelectMultiple]
I have two forms named GoodAtForm and PaidForForm. What these do is as follows... GoodAtForm Takes an input from a list in request.session['love'] and presents it to the user. Then user is presented with a CheckboXSelectMultiple fields so that users can select. After The form is submitted in the view, the user choices are then stored inside another list request.session['good']. 4.Another Form named PaidForForm uses that list for further asking of questions from users using CheckBocSelectMultiple and the selections are from the list ```request.session['good']. My problem is that I am unable to access output data inside the Forms to provide it to view. Input is working fine when initialised. My forms renders from the given list but the problem is that Form is not providing output. It says 'QueryDict' object has no attribute 'session' This is my GoodAtForm class GoodAtForm(forms.Form): def __init__(self, request, *args, **kwargs): super(GoodAtForm, self).__init__(*args, **kwargs) input_list = request.session['love'] self.fields['good'] = forms.MultipleChoiceField( label="Select Things You are Good At", choices=[(c, c) for c in input_list], widget=forms.CheckboxSelectMultiple ) View For the GoodAtForm def show_good_at(request): if request.method == 'POST': form = GoodAtForm(request.POST) #it is showing problem here. Throws an exception here if form.is_valid(): if not request.session.get('good'): request.session['good'] = [] request.session['good'] = … -
Custom template tag: where to actually put it in the template?
After completing the Django tutorial, I am trying to follow the instructions in the "Inclusion tags: section of https://docs.djangoproject.com/en/2.2/howto/custom-template-tags/ . I am not familiar with the syntax of template tags and I wasn't able to figure out reading the documents either. polls_extra.py : from django import template from django.template.loader import get_template register = template.Library() @register.inclusion_tag('results.html') def show_results(poll): choices = poll.choice_set.all() return {'choices': choices} results.html : <h1>{{ question.question_text }}</h1> {% load poll_extras %} <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li> {% endfor %} </ul> <a href= {% show_results poll %}>Vote again?</a> Then when I submit a poll choice I get the error: AttributeError at /polls/1/results/ 'str' object has no attribute 'choice_set' How should it actually be included in the html? -
Models trained with TensorFlow are not available in Django
Restoring from checkpoint failed. This is most likely due to a Variable name or other graph key that is missing from the checkpoint. Please ensure that you have not altered the graph expected based on the checkpoint. Original error: Key bias_1 not found in checkpoint [[node save_1/RestoreV2 (defined at Programing\web_programing\django\django-vegiter\predict\views.py:20) ]] Trace Back saver.restore(sess, save_path) … err, "a Variable name or other graph key that is missing") Run in Python virtual environment Django 2.2.5 Keras-Applications 1.0.8 Keras-Preprocessing 1.1.0 numpy 1.17.1 pandas 0.25.1 tensorboard 1.14.0 tensorflow 1.14.0 tensorflow-estimator 1.14.0 termcolor 1.1.0 Create your views here. def index(request): X = tf.placeholder(tf.float32, shape=[None, 4]) Y = tf.placeholder(tf.float32, shape=[None, 1]) W = tf.Variable(tf.random_normal([4, 1]), name="weight") b = tf.Variable(tf.random_normal([1]), name="bias") hypothesis = tf.matmul(X, W) + b saver = tf.train.Saver() model = tf.global_variables_initializer() sess = tf.Session() sess.run(model) save_path = "./model/saved.cpkt" saver.restore(sess, save_path) if request.method == "POST": avg_temp = float(request.POST['avg_temp']) min_temp = float(request.POST['min_temp']) max_temp = float(request.POST['max_temp']) rain_fall = float(request.POST['rain_fall']) price = 0 data = ((avg_temp, min_temp, max_temp, rain_fall), (0, 0, 0, 0)) arr = np.array(data, dtype=np.float32) x_data = arr[0:4] dict = sess.run(hypothesis, feed_dict={X: x_data}) price = dict[0] else: price = 0 return render(request, 'predict/index.html', {'price': price}) POST Variable Value csrfmiddlewaretoken 'BeE48x03YbOY3tIC7eF8L0tKrZME' avg_temp '24' min_temp '12' max_temp '31' … -
Im tried to try many solution to solve HTTP status code must be integer in django when pass varible by render
Dears I have 3 model and i want pass them to teplate by render since when i put third array i get error : HTTP status code must be an integer My model is Calss Dashwidget(models.Model): Wname=models.charfield(max_lenght=200) Categoryw=models.ForeignKey(category,related-name='categorydashboard',one_delete=models.CASCADE) preserve_default=false, sql_query=models.TextField('sql',blank=False) My veiw: def dashbaord(request): domain_list=domain.objects.all() Context={'domain_list', domain_list} Category_list= Category.objects.all() Contextcategory={'Category_list', Category_list} Widget_list=Dashwidget.objects.all() Contextwidget={'Widget_list', Widget_list} return render(request,"Dashboard.html",Context,Contextcategory,Contextwidget) -
render staticfiles django with react redux
I have a few objects saved on database that I received by Django RestFramework. That database have a few columns e one of them is ImageField. I already have all setup and my image field's response is "media/product_path.jpg". When I tried render that image field shows me a invalid image, with a image icon and the alt tag. In console from browser don't show the image path. { this.props.products.map(product => ( <tr key={product.id}> <th scope="row"> <img src="{product.image}" alt="product.image" /> </th> <th scope="row"> {product.name} </th> </tr> )) } APIProduct do Django: class APIProduct(APIView): parser_class = (FileUploadParser,) def get_queryset(self): return Product.objects.all().order_by('-created_at') def get(self, request, *args, **kwargs): products = Product.objects.all() serializer = ProductSerializer(products, many=True) return Response(serializer.data) def post(self, request, *args, **kwargs): file_serializer = ProductSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) urls.py: urlpatterns = [ path('', include(router.urls)), path('categories/', APICategory.as_view()), path('products/', APIProduct.as_view()), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to get file name of script passed to manage.py shell?
I'm running a script by passing it to ./manage.py shell: ./manage.py shell < script.py Inside the script.py is: import sys from os.path import basename print(sys.argv[0]) print(basename(__file__)) print(__file__) When I run ./manage.py shell < script.py, it does not print 'script.py' but: ./manage.py shell.py [full_path_to]/shell.py How can I output the actual name that is 'script.py'? -
How to get Stripe subscription id?
I'm new to python and Stripe. How to get the subscription id to process a cancelation? # Here is my views.py where I create the plan stripe.api_key = settings.STRIPE_SECRET_KEY if request.method == 'POST': try: token = request.POST.get('stripeToken') user = request.user plan = 'plan_xxxxxxx' order_number = x customer = stripe.Customer.create(description='Membership', source=token, email=user.email, plan=plan) charge = stripe.Subscription.create( customer=customer.id, items=[{'plan': plan}] ) In the view below, I have the customer information but not sure how to cancel. user = request.user cust_id = str(list(Premium.objects.filter(user=user).values_list('stripe_customer_id')))[3:-4] # this retrieves the customer information customer = stripe.Customer.retrieve(cust_id) # this does not work! stripe.Subscription.delete(customer['subscription']) This fails because and I get this error: KeyError: 'subscription' -
azure web app for containers uWSGI listen queue of socket full
My app running in a docker container on Azure Webapps for Containers (linux). I found out my server is getting error when listening queue increases. log: uWSGI listen queue of socket "127.0.0.1:37400" (fd: 3) full !!! **(101/100)** I have added '''--listen 4096''' option to increase the queue. but my server still throws error. log: uWSGI listen queue of socket "127.0.0.1:37400" (fd: 3) full !!! **(129/128)** some reference says need to increase net.core.somaxconn but I couldn't increase it. log: sysctl: error: 'net.core.somaxconn' is an unknown key Any idea what i am missing? Thanks