Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
PUT request not working in Django Rest - VueJS app
I'm trying to make a blog useing VueJS and Django with the REST Api (Ajax via Axios). I can send a "PUT" request without errors in the console bur it is not effecting the database, is link the method is not called. I also have a problem with setting by default the already-uploaded image in the input type="file" field. The code: Vuejs <template> <h1>ARTICOLO</h1> <form @submit="onSubmit"> <input type="text" name="title" placeholder="Titolo" v-model="form.title"> <input type="text" name="desc" placeholder="Descrizione" v-model="form.desc"> <input type="text" name="category" v-model="form.category"> <input type="file" name="image" @change="EditImage"> <input type="text" name="author" v-model="form.author"> <input type="text" name="author" v-model="form.slug"> <textarea name="text" v-model="form.text"></textarea> <p>{{ form }}</p> <button type="submit" @click= "onSubmit">Edit</button> </form> </template> <script> import axios from 'axios'; import { getAPI } from '../api' export default { data () { return{ Postslug: this.$route.params.Postslug, form: { title:"", desc:"", text:"", category:"", date:"", author:"", image:"", slug:"", }, selectedFile: '' } }, methods: { EditImage(event){ this.selectedFile = event.target.files[0] console.log(event); }, // Form method onSubmit(event){ const fd = new FormData(); fd.append('image', this.EditImage, this.EditImage.name) event.preventDefault(); axios.put(`http://127.0.0.1:8000/blog/api/edit/${this.Postslug}`, this.form).then(response => { this.form.title = response.data.title this.form.desc = response.data.desc this.form.text = response.data.text this.form.image = this.fd this.form.category = response.data.category this.form.author = response.data.author this.form.slug = response.data.slug }) .catch(err => { console.log(err) }) }, }, created() { getAPI.get(`blog/api/edit/${this.Postslug}`) .then(response => { this.form.title … -
How to use a Formset with Django_Tables2
I love using django_tables2 but I've hit a bit of a snag. I have an edit page with a standard django form for updating a member's details. Within this form there is a table of addresses for the current member which I can render easily with django_tables2 using the following code. from tables.py class AddressTable(tables.Table): address1 = tables.Column(attrs={'th':{'class':'centered nodec'}, 'td':{'data-title':'Address 1'}}) address2 = tables.Column(attrs={'th':{'class':'centered nodec'}, 'td':{'data-title':'Address 2'}}) address3 = tables.Column(attrs={'th':{'class':'centered nodec'}, 'td':{'data-title':'Address 3'}}) address4 = tables.Column(attrs={'th':{'class':'centered nodec'}, 'td':{'data-title':'Address 4'}}) address5 = tables.Column(attrs={'th':{'class':'centered nodec'}, 'td':{'data-title':'Address 5'}}) postcode = tables.Column(attrs={'th':{'class':'centered nodec'}, 'td':{'data-title':'Postcode'}}) class Meta: model = Address fields = ('address1','address2','address3','address4','address5','postcode',) template_name = 'django_tables2/bootstrap.html' attrs={'id':'addresslist', 'class': 'table table-noborder no-table'} and I pass the data from my view like like this from views.py f = AddressListFilter(request.GET, queryset=Address.objects.all(),request=request) addresstable = AddressTable(f.qs) However, the page needs to allow the user to be able to dynamically add as many extra address records as they wish (which I can use javascript to do this) but I then need to pass the entire table, complete with additional address records, back to django for processing when the user hits the submit button within the form. From what I can gather I should be using a django formset to achieve this … -
How to keep the API running and also Consume Pika (RabbitMQ) parallelly
I have a set of API endpoints serving in the Django app. But I also want to consume a queue(from Pika, a message broker) and execute a function when there is a message in the queue. If I consume a queue, it is blocking the thread and API stops serving. I'm not sure how to achieve this. Do I have to use [background tasks][1] or use Multi-Threading to create a new thread and use it to consume? Any sample code to achieve this is much appreciated. [1]: https://django-background-tasks.readthedocs.io/en/latest/#:~:text=In%20Django%20Background%20Task%2C%20all,process)%20to%20execute%20the%20tasks -
How do I properly implement Django formsets with a CreateView ( Class Based View )?
And thanks in advance for any suggestions. I have been playing around with how to properly implement formsets with a CreateView for a couple of days and I'm stuck. Here is my code. My Models: class Team(models.Model): team_name = models.CharField(max_length=264,null=False,blank=False) class Player(models.Model): player_name = models.CharField(max_length=264,null=False,blank=False) team = models.ForeignKey(Team,null=True,on_delete=models.CASCADE) My View: class CreateTeamView(LoginRequiredMixin,CreateView): model = Team form_class = CreateTeamForm template_name = 'create_team.html' def get_context_data(self, **kwargs): context = super(CreateTeamView, self).get_context_data(**kwargs) if self.request.POST: context['new_player'] = NewPlayerFormSet(self.request.POST) else: context['nwe_player'] = NewPlayerFormSet() return context def get_form_kwargs(self, *args, **kwargs): kwargs = super(CreateTeamView, self).get_form_kwargs() kwargs['user'] = self.request.user return kwargs def form_valid(self, form): context = self.get_context_data() new_player_form = context['new_player'] if new_player_form.is_valid(): self.object = form.save() new_player_form.instance = self.object new_player_form.save() instance = form.save() else: return self.render_to_response(self.get_context_data(form=form)) My Forms: class CreateTeamForm(forms.ModelForm): class Meta: model = Team exclude = [] NewPlayerFormSet = inlineformset_factory(Team, Player, extra=1, fields=['player_name',]) My HTML: <div="players> <div="add_players"> {{ new_player.management_form }} {% for form in new_player %} {{ form.id }} {{ form.player_name }} </div> </div> My form is saving one player, but when I try to update the code to save more than one player with the initial CreateView, it only recognizes the first contact. I have overridden the BaseInlineFormset to do validation as shown below.... class NewPlayerFormSet(NewPlayerFormSet,BaseInlineFormSet): player_name = … -
How do you format a Django datepicker as ISO 8601?
We need to display dates in ISO 8601 (yyyy-mm-dd) format throughout our Django site. The dates that we are getting from the database show correctly, however date pickers do not. When I run the django test server in ubuntu, the datepicker appears to use the locale that the OS is set to. When I run the same code in Windows, it uses dd/mm/yyyy. The various input_formats args appear to be getting overridden somehow, even though I have set them everywhere I can find. Is it possible to force datepickers to display yyyy-mm-dd regardless of client settings? If so, how? Here is the code we have so far. forms.py ... class DateInput(forms.DateInput): input_type = "date" input_formats = ["%Y-%m-%d"] options = { "format": "%Y-%m-%d", "autoclose": True } class RegistrationForm(forms.Form): full_name = forms.CharField(max_length=255, required=True) preferred_name = forms.CharField(max_length=255, required=False) email = forms.EmailField(required=True) password = forms.CharField( max_length=255, required=True, widget=forms.PasswordInput, help_text=password_validation.password_validators_help_text_html(), ) birth_date = forms.DateField(required=True, widget=DateInput, input_formats=["%Y-%m-%d"]) ... settings.py ... LANGUAGE_CODE = "en-us" TIME_ZONE = "UTC" USE_I18N = True USE_L10N = False USE_TZ = True DATE_INPUT_FORMATS = [ '%Y-%m-%d' ] DATETIME_INPUT_FORMATS = [ '%Y-%m-%dT%H:%M:%S' ] DATETIME_FORMAT = [ '%Y-%m-%dT%H:%M:%S' ] ... Full code available on GitHub. -
How to test Django messages for a Class Based FormView?
I am struggling to find the proper way to test a FormView. I would like to check if the message (generated through django.contrib.messages) is rendered when the user is not authenticated. I have already read about RequestFactory, Client, Mock, Middleware and I was not able to implement this test in CBV FormView. The problem is not about authenticating user particularly, I want to use the logic in other fields also to test other messages. Here is my code: View: class MyView(FormView): form_class = MyForm template_name = 'app/welcome_template.html' def form_valid(self, form): form_data = form.cleaned_data auth = LDAPBackend() user = auth.authenticate(self.request, username=form_data['login_field'], password=form_data['password_field']) if user: return super(MyView, self).form_valid(form) else: messages.add_message(self.request, messages.WARNING, 'some warning' + str(form_data['other_field'])) return self.form_invalid(form) Form: class MyForm(forms.Form): login_field = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Login', 'class': 'form-control form-control-sm'}), label='Login:', max_length=20) password_field = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password', 'class': 'form-control form-control-sm'}), label='Password:', max_length=20) other_field = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Select ...', 'class': 'form-control form-control-sm', 'max': '99999999'}), label='Other:') Template: <form autocomplete="off" onsubmit="$('#ModalCenter').modal({backdrop: 'static', keyboard: false})" action="." target="_top" method="post"> {% csrf_token %} <div class="row"> <div> {% if messages %} {% for message in messages %} <div class="alert {% if message.tags %}alert-{{ message.tags }}{% endif %}" role="alert">{{ message }}</div> {% endfor %} {% endif %} </div> <div class="form-group mt-2"> {{ form.login_field.label_tag }} {{ … -
Django Form and two forms with foreign key
I have these models: class Customers(models.Model): ID = models.AutoField(primary_key=True) ... def __str__(self): return str(self.ID) class CustomerAddresses(models.Model): ID = models.AutoField(primary_key=True) ... CustomerNoID = models.ForeignKey('Customers', on_delete=models.CASCADE) def __str__(self): return str(self.ID) and my view: def add_customer_view(request): user_id = request.user.id last_customerno = Customers.objects.filter(UserID=user_id).order_by('CustomerNo').last() if not last_customerno: # return '0001' last_customerno = 1000 if last_customerno == 1000: customerno_int = 1000 else: customerno_int = last_customerno.CustomerNo + 1 # if this is a POST request we need to process the form data if request.method == 'POST': customer_form = CustomerForm(request.user.id, request.POST) customer_address_form = CustomerAddressesForm(request.user.id, request.POST) if customer_form.is_valid(): new_customer = customer_form.save(commit=False) new_customer.save() if customer_address_form.is_valid(): new_address = customer_address_form.save(commit=False) new_address.CustomerNoID = new_customer new_address.save() return HttpResponseRedirect('/backend/kunder/') else: customer_form = CustomerForm(request.user.id, initial={'CustomerNo': customerno_int}) customer_address_form = CustomerAddressesForm(request.user.id) return render( request, 'backend/add_customer.html', { 'title': 'WestcoastShop - Backend', 'customer_form': customer_form, 'customer_address_form': customer_address_form } ) But just the Customer is creating not the address I think the form is missing the CustomerNoID and I think I got the right way but after 6 hrs I give up maybe here is a smart guy how finds the error. regards. -
Python / Django - Generating API Documentation - Not using Django Rest
I am working on a Django project that does not use Django Rest On top of this code base I am trying to build a framework to autogenerate swagger documentation From this S.O. Post I am able to get the available Urls: from django.urls import get_resolver urls = get_resolver().reverse_dict urls is a MultiValueDict, here are the first few items in the Dict: MultiValueDict: { <function create_demo at 0x10f6a3820>: [( [('api/v1/create-demo', [])], 'api/v1//create\\-demo$', {}, {} )], 'create_demo': [( [('api/v1/create-demo', [])], 'api/v1/create\\-demo$', {}, {} )], <function users_detail at 0x10f67d280>: [( [('api/v1/users/users/%(user_id)s', ['user_id'])], 'api/v1/users/users/(?P<user_id>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$', {}, {'user_id': <django.urls.converters.UUIDConverter object at 0x10bc3c6a0>} )], 'users_detail': [( [('api/v1/users/users/%(user_id)s', ['user_id'])], 'api/v1/users/users/(?P<user_id>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$', {}, {'user_id': <django.urls.converters.UUIDConverter object at 0x10bc3c6a0>} )] It appears the keys for this dict are a reference to a view function, followed by the url "name" for that function, and the values are lists containing the relative url path and params. My thought is to loop through each function reference and create an entry for the swagger doc. Inside each view function, I will define vars named RequestSchema and ResponseSchema. Ideally I can access those vars, from the function reference, and add that data to the swagger doc as well. The goal is to have documentation that … -
NoReverseMatch at /search/
ERROR Message ,I think i am getting this error maybe because of the link i mentioned in the stores.html. NoReverseMatch at /search/ Reverse for 'product_details' with arguments '('', 'product-5')' not found. 1 pattern(s) tried: ['detailed/(?P[-a-zA-Z0-9_]+)/$'] Request Method: GET Request URL: http://localhost:8000/search/?search=Circe Django Version: 3.0.5 Exception Type: NoReverseMatch Exception Value: Reverse for 'product_details' with arguments '('', 'product-5')' not found. 1 pattern(s) tried: ['detailed/(?P[-a-zA-Z0-9_]+)/$'] Exception Location: C:\Users\BHAVIN\Envs\test\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 677 ***URLS.py*** from django.urls import path from django.contrib.auth import views as auth_views from . import views #from .views import ItemDetailView urlpatterns = [ #Leave as empty string for base url path('', views.stores, name="stores"), path('cart/', views.cart, name="cart"), path('checkout/', views.checkout, name="checkout"), path('update_item/', views.updateItem, name="update_item"), path('process_order/', views.processOrder, name="process_order"), path('register/', views.registerPage, name="register"), path('login/', views.loginPage, name="login"), path('logout/', views.logoutUser, name="logout"), path('order/', views.order, name="order"), # path('detail/<slug>/',ItemDetailView.as_view(), name='detail'), path('about/', views.about, name='about'), path('detailed/<slug:slug>/',views.product_details, name='product_details'), path('search/', views.search, name="search"), path('reset_password/', auth_views.PasswordResetView.as_view(template_name="store/password_reset.html"), name="reset_password"), path('reset_password_sent/', auth_views.PasswordResetDoneView.as_view(template_name="store/password_reset_sent.html"), name="password_reset_done"), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name="store/password_reset_form.html"), name="password_reset_confirm"), path('reset_password_complete/', auth_views.PasswordResetCompleteView.as_view(template_name="store/password_reset_done.html"), name="password_reset_complete"), ] Stores.html {% extends 'store/base.html' %} Search {% block content %} {% for product in qs %} <div class="col-md-6 col-lg-3 ftco-animate"> <div class="product"> <a href="{% url 'product_details' detailed product.slug %}" class="add-to-cart d-flex justify-content-center align-items-center text-center"> <span class="img-prod"><img class="img-fluid" src="{{product.imageURL}}" alt="" /> {% if product.on_sale %} <span class="status">on Sale</span> {% endif %} <div … -
Django response to client when process finished
I have a question to python django framework. I have situation that i am sending request from android phone to my service to find opponent for my online game and when it will be found after some time, server should send back information about that to my phone. The problem is that i dont know how to send back response with rest. There is any callback function or something that i can use to it or i should rather use websockets or something like this? -
Mozilla Django OpenID Logout does not revoke token
I've been working to integrate a django app with mozilla-django-oidc and I can't seem to figure out how to log out of the thing correctly. On my main page I have <form action="{% url 'oidc_logout' %}" method="post"> {% csrf_token %} <input type="submit" value="logout"> which provides the logout assuming a user is logged in. Logging in seems to work well enough. In my settings I'm providing the logout configurations OIDC_OP_LOGOUT_ENDPOINT = cfgs.get("LOGOUT_ENDPOINT") OIDC_OP_LOGOUT_METHOD = "test_app_2.openid.logout" LOGOUT_REDIRECT_URL = reverse('post-logout') POST_LOGOUT_URL = cfgs.get("LOGOUT_REDIRECT") Which are my okta oidc logout endpoint, the method that I wrote to create the correct logout url and logout redirect. I created a POST_LOGOUT_URL variable so I can access the post-logout url elsewhere. openid.logout looks like this def logout(request): id_token = str(request.COOKIES['csrftoken']) logout_request = \ f'{settings.OIDC_OP_LOGOUT_ENDPOINT}?id_token_hint={id_token}' \ f'&post_logout_redirect_uri={settings.POST_LOGOUT_URL}' return logout_request Which is the correct logout url configuration for oidc. I've tested all this through a flask app and it all works just fine. Why don't I just use flask? It's a long story. I'd rather use Django... In my views.py I have class LogoutView(OIDCLogoutView): def get(self, request): return self.post(request) Which I confess to have grabbed from another post and I'm not entirely sure how it works with my urls … -
Testing views with pytest, how to mock celery task
I faced a problem while mocking celery task. Hope someone will be able to help me conftest.py import pytest @pytest.fixture def api_client(): from rest_framework.test import APIClient return APIClient() views.py class SomeViewSet(ModelViewSet): def create(self, request, *args, **kwargs): serializer = self.get_serializer_class()(data=request.data) if serializer.is_valid(): serializer.save() my_celery_task.delay(serializer.instance.pk) return Response(serializer.data, status=status.HTTP_201_CREATED) tests.py @patch('requests.post') @pytest.mark.django_db def test_create(api_client): response = api_client.post(reverse('withdraw-act-list'), data=request_data, format='json') assert response.status_code == 201 I have tried severals @patch('requests.post') @patch.object(my_celery_task, 'delay'), but everytime got AssertionError: assert <MagicMock name='post.post().status_code' id='140584951434880'> == 201 How to fix this? Is there a way to mock the celery task and get valid response in the test -
how to show a pdf received through an API by Request Python
good, I have a problem I have to develop an application that shows a PDF in a template and the truth is that I do not implement it, for this project I am consuming an API, through an authentication by Token, the thing is that when I access the API Returns the PDF but it does not show me in the Template, if I use METOSO PRINT POS in the Terminal I "sample", please if someone knows some way to implement it or any suggestions I would greatly appreciate it or my information on this topic, it can be said That I am new to Django and I have intermediate programming bases. Result in the terminal from django.shortcuts import render, HttpResponse, redirect from miapp.models import Usuario from django.contrib import messages from django.contrib.auth import authenticate, login, logout import requests def access(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request,user) messages.success(request, 'Te has identificado correctamente') return redirect('inicio') else: messages.warning(request, 'No te has identificado correctamente') return render(request, 'index.html',{ 'form':'Identifícate' }) def service(request): return render(request, 'inicio.html',{ 'title':'Inicio' }) class Token(object): def __init__(self, url, payload): self.url = url self.payload = payload headers … -
Django DRF - jwt vs simplejwt
I have been ramping up on Django Rest Framework and JWT authentication through tutorials that point to django-rest-framework-jwt but while researching how to customize JWT validation, realized that there is a newer implementation django-rest-framework-simplejwt. The older jwt package does not have a commit since 2017 but simple-jwt is actively maintained and developed, and from what I can find, has better security features. It is also the recommended link in the DRF documentation. I could not find a relevant post on S/O but I found that JoelGoh92 in this git issue summarizes the problem well: 1. In most JWT implementations, an access token + a refresh token is returned. Otherwise the other option, if only a single token is desired, is the sliding token approach. With simple-jwt, the jwt can be configured to either of these implementations, whichever is required. 2. With the current django-rest-framework-jwt supported by rest-auth, the only approach available is similar to the sliding token approach, except that it has no way to blacklist a previously generated jwt token, e.g. by logout on user end. On the other hand, simple-jwt provides a way to perform this blacklisting of invalid tokens. I'm curious to know whether the lack of … -
Config for 'Cache' in settings.CACHES missing
I have configured cache in settings.py in my Django project as follows: CACHE_MIDDLEWARE_ALIAS = 'Cache' CACHE_MIDDLEWARE_SECONDS = 60 CACHE_MIDDLEWARE_KEY_PREFIX = '' CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': '127.0.0.1:11211', } } Cache service is running after I typed: $ memcached -p 11211 & But when I try to run server, the following error shows up: django.core.cache.backends.base.InvalidCacheBackendError: Could not find config for 'Cache' in settings.CACHES What I am doing wrong? -
Converting <class 'str'> type to json in django
I want to convert this queryset result data; [{"g_id": 1, "corX": 2432, "corY": 1376, "date": "2021-03-30T15:17:00+03:00"}, {"g_id": 2, "corX": 2432, "corY": 2432, "date": "2021-03-29T11:55:50+03:00"}] to json format like; { "data": [ {"g_id": 1, "corX": 2432, "corY": 1376, "date": "2021-03-30T15:17:00+03:00"}, {"g_id": 2, "corX": 2432, "corY": 2432, "date": "2021-03-29T11:55:50+03:00"} ] } in function django without return Jsonresponse. I can't do it. -
Django - annotate price= "price_A" or "price_B"
I have multiple fields that stores the same value type (price) from different sources. class Product... price_amazon = ... price_ebay = ... price_etsy = ... @property def price... return self.price_amazon or self.price_ebay or self.price_etsy I'm looking for a way to annotate price to each Product from queryset. It should behave exactly as the price property. price is either price_amazon, price_ebay or price_etsy - the first not None value. How would you do that? I tried: Product.objects.all().annotate(price=F('price_amazon') or F('price_ebay') or F('price_etsy')) which raises: AttributeError Traceback (most recent call last) ~/PycharmProjects/.virtualenvs/freedomprogress.cloud/lib/python3.8/site-packages/IPython/core/formatters.py in __call__(self, obj) 700 type_pprinters=self.type_printers, 701 deferred_pprinters=self.deferred_printers) --> 702 printer.pretty(obj) 703 printer.flush() 704 return stream.getvalue() ~/PycharmProjects/.virtualenvs/freedomprogress.cloud/lib/python3.8/site-packages/IPython/lib/pretty.py in pretty(self, obj) 392 if cls is not object \ 393 and callable(cls.__dict__.get('__repr__')): --> 394 return _repr_pprint(obj, self, cycle) 395 396 return _default_pprint(obj, self, cycle) ~/PycharmProjects/.virtualenvs/freedomprogress.cloud/lib/python3.8/site-packages/IPython/lib/pretty.py in _repr_pprint(obj, p, cycle) 698 """A pprint that just redirects to the normal repr function.""" 699 # Find newlines and replace them with p.break_() --> 700 output = repr(obj) 701 lines = output.splitlines() 702 with p.group(): ~/PycharmProjects/.virtualenvs/freedomprogress.cloud/lib/python3.8/site-packages/django/db/models/query.py in __repr__(self) 261 262 def __repr__(self): --> 263 data = list(self[:REPR_OUTPUT_SIZE + 1]) 264 if len(data) > REPR_OUTPUT_SIZE: 265 data[-1] = "...(remaining elements truncated)..." ~/PycharmProjects/.virtualenvs/freedomprogress.cloud/lib/python3.8/site-packages/django/db/models/query.py in __len__(self) 267 268 def __len__(self): --> … -
How do i mock patch a nested method call
So this is quite a 'complex' test case i want to tackle. I have a Django Model, named Store and that store has many methods and fields. I want to test a specific method of the Store Model, beging get_orders(self) That get_orders(self) method calls on an external API trough an instance of module. So we have the MarketPlace module. That Marketplace module has several methods like, get_orders(), create_order(), etc. The Store model has an attribute that is an instance of the Marketplace module and via that route the method is called. How do i test the Store.get_orders(self)? #/app/stores/models.py class Store(models.Model): store_name = models.CharField(max_length=100, blank=False) marketplace_api_key = models.CharField(max_length=100, blank=False) @property def marketplace_instance(self): markets = MarketPlace(api_key=self.marketplace_api_key ) return market def get_orders(self): # this is the method i want to mock open_orders = self.marketplace_instance.get_open_orders() #/app/controllers/MarketPlace/MarketPlace.py class MarketPlace(models.Model): api_key = models.CharField(max_length=100, blank=False) def get_open_orders(self): url = f'https://marketplace.com/?apikey={self.api_key}' r = requests.get(url, headers=headers) if r.status_code == 200: return r.json() else: return None #/app/stores/tests/test_models.py class StoreTests(TestCase): @classmethod def setUpTestData(cls): cls.store = StoreFactory() cls.mock_open_order_patcher = patch('controllers.MarketPlace.Marketplace.MarketPlace.get_open_orders') cls.mock_open_order = cls.mock_open_order_patcher .start() @classmethod def tearDown(cls) -> None: cls.mock_open_order_patcher .stop() def test_get_orders_marketplace(self): orders_response = {} self.mock_open_order.return_value = MagicMock(ok=True) self.mock_open_order.return_value.json.return_value = orders_response assert self.store.get_orders() -
The Group could not be created because the data didn't validate
I am building a ChatApp and I am stuck on an Error. The error is keep showing :- The Group could not be created because the data didn't validate. When i try to submit form without fill the form. Then it keep showing error The Group could not be created because the data didn't validate. views.py def create_chat(request): p = request.user.profile you = p.user if request.method == 'GET': if request.user.is_authenticated: chat_boxes = [] groups = [] return render(request, 'chat.html', {'chat_boxes': chat_boxes, 'groups': groups}) else: form = ChatGroupForm(data=request.POST, files=request.FILES) group = form.save(commit=False) group.author = request.user group.save() group.members.add(request.user) group.group_admins.add(request.user) return redirect('chat_group', pk=group.id) What have i tried I also tried by putting if form.is_valid() but it shows local variable 'group' referenced before assignment I also saw many answers but nothing worked for me. Any help would be appreciated. Thank You in Advance. -
Why is pre_save signal not working at all?
Why is my pre_save signal not working? I'm sure that there are no errors but it does not work. I tried adding new object in my model throuh django admin but it did not work either. My code: from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from .models import PostImages #signals.py @receiver(pre_save, sender=PostImages) def delete_file_on_change_extension(sender, instance, **kwargs): print('test') #I see nothing in console #Do something... #models.py class PostImages(models.Model): post_id = models.ForeignKey(Post, on_delete=models.CASCADE) image = models.ImageField(upload_to=user_directory_path, null=True, blank=False) Also, it appeared to work when I put signal code in models.py but i could not get it further because it caused mistakes like django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. -
Adding a search field for Token section in Django Admin
I'm using the Django rest framework and I need to manually delete a token that belongs to a specific user using the Django admin. But the problem is it's hard to find the relevant token of a user when there are thousands of tokens. So I need to add a search to the token section then I can search the token using the user's Email. How I can add an search for the token section in the Django admin. -
Particular category's product listing in one shared html page
I am creating ecommerce site in django , I have large number of categories so when user clicks particular category in one html page It has to redirect to another page and show the products of selected category For example there should be one html page called selectedCategoryProducts.html and when user clicks drinks at category listing at Home page it has to redirect to the selectedCategoryProducts.html and show the products under drinks , when user clicks medicines it should share the same html page to show the products under medicines I don't want to create html page for every category that i'm having Is there any idea to do that home.html Category Listing {% for category in allCategory %} <li class="dropdown" > <a href="#" class="dropdown-toggle" data-toggle="dropdown">{{category}} <b class="caret"></b></a> <ul class="dropdown-menu multi-column columns-3"> <div class="row"> {% for subcategory in subCategories %} {% if subcategory.category == category%} <div class="col-sm-3"> <ul class="multi-column-dropdown"> <h6>{{subcategory.subCatName}}</h6> {% for types in productCategories %} {% if types.subCategory == subcategory %} <li><a href="dresses.html">{{types}}<span>New</span></a></li> {% endif %} {% endfor %} </ul> </div> {% endif %} {% endfor %} <div class="clearfix"></div> </div> </ul> </li> {% endfor %} selectedCategory.html {% for product in instanceselectedCategory %} <h2>product.productName</h2> {% endfor %} -
django framework can't create authentication token in google cloud
I can't create a token for an user manually throught django admin site (https://admin/). I have built an user accounts on a django framework allocated in google cloud server, as a GAE app. In order to add user accounts I use a third-party app for django called "rest_framework", the problem comes when I try to create a token for a created user in admin site, error 500 appear and no idea how to find the problem. The framework also has been tested on a local machine (my computer) and works correctly, but for some reason it doesn't work in google cloud. The added code of each file is showing as follows: settings.py from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = ... DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'django.contrib.sites', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'KhalilApp.apps.KhalilappConfig', #This is my app on django 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'DjangoServer.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR,'KhalilApp/Mapilib'), os.path.join(BASE_DIR,'static'), os.path.join(BASE_DIR,'KhalilApp/templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'DjangoServer.wsgi.application' import pymysql pymysql.version_info = … -
mysql is not available in django.db.backends (django)
trying to connect to the mysql and trying to do makemigrations. but getting this error: django.core.exceptions.ImproperlyConfigured: 'django.db.backends.mysql' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'oracle', 'postgresql', 'sqlite3' my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '****', 'USER': 'root', 'PASSWORD': '****', "HOST": '****', 'PORT': '****' } } Thanks in advance -
Django benchmark
For my research, I am trying to benchmark Django framework capacity. I am running the server in my own pc which has Intel core i7 processor with 12 core. If I run django with the builin server, it can server, it can server ~3000 request/30s.(HTML is just a "hello world" page). I tried to run Django with Gunicorn. But to my surprise, it does not increase the server capacity. Even if I use 24 worker process, it still can serve ~3100 requests/30s. Does this number seem right? Because compared to other languages, it seems very low. I want to make sure if I am doing it right.