Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
module' object is not callable (TypeError at /add/2/ ')
i am facing this problem while pressing on add to cart button please help... from HomePage import Mycart //its directory in homepage app from .Mycart import Mycart from .models import Product from .models import Category ...............these are header files and error lies here @require_POST def cart_add(request, product_id): //the line bellow is an error destination line //// cart_var = Mycart(request) # create a new cart object passing it the request object product = get_object_or_404(Product, id=product_id) form = CartAddProductForm(request.POST) if form.is_valid(): cd = form.cleaned_data cart_var.add(product=product, quantity=cd['quantity'], update_quantity=cd['update']) return redirect('pages:checkout') module' object is not callable -
Django REST Framework: Why Adding IsAuthenticated Permissions Only Threw 500 Internal Error Instead of 401 / 403 Errors?
My original backend API based off Django REST Framework was working without any security measures implemented. Now I am implementing a JWT Token Authentication process, but realised the ever-bugging problem on the backend-Django side was that once I have added "IsAuthenticated" to "'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated')" , the page that is thrown from Django is consistently a 500 Internal Error, instead of a 401/403 Authenticated Error, of which I may at least know how to move forward in resolving. Thus, I hope someone can help to point me some direction in resolving it. I have been trying for the last 5-days to implement a JWT Token, Machine-to-Machine verification, with zero-user account, and purely based on a Token authorization access, and have sort-of sorted out most of the front-end request access process via Auth0. The process by which I presumed works based on what I have read from Auth0 API: Client Browser sends request to Auth0 token authentication API Auth0 replies with Token Client Browser uses replied Token to send as Authorization Header to backend API Server API replies with result data. The current problem I do realised is that upon Step 4, is that my server kept throwing 500 Errors instead … -
path : Django 2.2 path converter
I must miss something on how to work with path (not the function, the path converter). I don't understand why the None value in the following : I have an url : urlpatterns = [ ... re_path(r'(<path:current_path>)?', views.index, name='index'), ... ] A view : def index(request, current_path): logger.error(f'current_path : {current_path}') path = request.path ... Everything functions except that current_path value remains None, whatever is the given path, while request.path holds the correct value. Why ? -
How to replace django form tag with html input?
How to replace the default django form fields - {{form.fields}} with html tags - <input type="text"> I thought of hiding this default {{form.fields}} and link these with <input> fields so that i can easily customize CSS and JS. How can i acheive this? Currently i am styling this form with bootstrap with the django widgets in forms.py. I need to loop name of the students in the {{form.student}}, since it is an attendance form. An alternatives with same django form tags is also appreciated. Thanks in advance! -
How to request a resource from a server with Electron Download Manager?
We are developing an Electron client software where we need to get some configuration files (...) which are stored on our server running Django. As we want to get specific config files for each user, we need a login for the transfer. This is the code we are using in the Electron client (using Electron Download Manager): DownloadManager.download({ url: "http://" + SERVER_NAME + "/sessions/" + USER_ID.toString() + "/downloadConf", path: "config", onLogin: (authInfo, callback) => { callback('USERNAME', 'PASSWORD'); }, }, function (error, info) { if (error) { console.log(error); } }); Obviously all caps variables are assigned in the code above this snippet. In Django we have the route and view working (if you login with a user and navigate to this URL you get the files as HTTP response), but when trying to get it from the client by the code above there is no error message. This is what we configured the Django views head to: @login_required def download_conf(request, user_id): We wanted to use this with bulkDownload at first but as it didn't work, we built this small example to test it, but even this doesn't work. -
Boto3 Authorization on IIS
I'm setting up a Django application on IIS with boto3. I got the application running however I'm unable to query any data from AWS due to no profile configuration being detected. I tried running the application as a service account with AWS permissions. Giving the account R/W permissions to folder. Adding AWSProfileName and AWSProfilesLocation to web.config file I have double checked all common issues regarding this error, however, I think that my configuration might be wrong (perhaps in the web.config file) Web.Config file: <add key="AWSProfileName" value="Name_of_profile"/> <add key="AWSProfilesLocation" value="Path_to_credentials_folder"/> The error I'm getting: The config profile (Profile_Name) could not be found -
How to use LimitOffSetPagination instead of PageNumberPagination in Django Rest Framework?
I have written a code in Python using Django Rest Framework to fetch data from database(MySql) and view it in browser using Pagination(LimitOffSetPagination).But It is not working fine.But when I used PageNumberPagination it was working great...so I am posting my new code.Commented parts of my code is actually for PageNumberPagination. So just ignore it. Please tell me the necessary changes needed and help me out. The error coming is - """" Exception Value: index() missing 1 required positional argument: 'request' """".... view.py from rest_framework.pagination import PageNumberPagination from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from rest_framework.pagination import LimitOffsetPagination @api_view(['GET','POST']) def index(self, request): if request.method=='GET': all_dataobj=fetchdata.objects.all() page = self.paginate_queryset(all_dataobj) if page is not None: pserializer = self.get_fetchdataSerializers(page, many=True) return self.get_paginated_response(pserializer.data) pserializer = self.get_fetchdataSerializers(all_dataobj, many=True) return Response(pserializer.data) # paginator = StandardResultsSetPagination() # result_page = paginator.paginate_queryset(all_dataobj, request) # pserializer=fetchdataSerializers(result_page,many=True) # return paginator.get_paginated_response(pserializer.data) elif request.method=='POST': serializer=fetchdataSerializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data,status=status.HTTP_201_CREATED) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) settings.py REST_FRAMEWORK = { # 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'PAGE_SIZE': 10 } urls.py urlpatterns = [ path('', m.index, name='index'), ] -
How to join a model and get a name from second model via joining
I have a students table and a university table. I seem to be unable to retrieve the university name based on the university_id the student has Database: students: id, first_name, last_name, university_id 0, bob, jones, 12 1, Tim, Smith, 13 university: id, name 12 Harvard 13 Stanton 14 N/A Models.py from django.db import models class University(models.Model): name = models.CharField(max_length=50) class Meta: verbose_name = "University" verbose_name_plural = "Universities" #__unicode__ def __str__(self): return self.name class Student(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) university = models.ForeignKey(University, on_delete=models.DO_NOTHING) class Meta: verbose_name = "Student" verbose_name_plural = "Students" #__str__ def __str__(self): return '%s %s' % (self.first_name, self.last_name) views.py class View_all_apiview(APIView): def get(self, request, *args, **kwargs): students_q = Student.objects.all().prefetch_related('university') return JsonResponse(students_q.values(), safe=False) I tried getting the university name using students_q.name, but that gives an error. -
Send stock prices to Django using ibapi
I am using ibapi to publish stock prices on a website build using django. I am new to both django and ibapi. On googling I know that channels can be used for real time data. Code For ibapi is - class MyWrapper(EWrapper): def error(self, reqId, errorCode, errorString): print("Error. Id: " , reqId, " Code: " , errorCode , " Msg: " , errorString) def tickPrice(self, reqId, tickType, price, attrib): print("Tick Price Ticker Id:", reqId, "tickType:", TickTypeEnum.to_str(tickType), "Price:", price) def tickSize(self, reqId, tickType, size): print("Tick Size. Ticker Id:", reqId, "tickType:", TickTypeEnum.to_str(tickType), "Size:", size) code of consumer class is - class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name self.prices = '00' # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) #Receive message from WebSocket async def receive(self, text_data): # print(self.prices) self.process() text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': text_data } ) #Receive message from room group async def chat_message(self, event): message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message })) def process(self): wrapper = MyWrapper() app = … -
Override the admin interface
I would like to override the django admin add/update just by adding a button that renders other inputs on the same form. For example the admin can Add phone numbers of Employee just by clicking the button new form renders at the button for adding new Phone number. Like in this example we have a One-to-many relation between Employee and PhoneNumber model. any ideas or example will be helpful. -
Failing to turn queryset into JSON with a many2many model
I want to serialize a simple queryset but I am failing. I have a model that has a many to many relationship and I want to display only some fields. My models: class BuildingGroup(models.Model): description = models.CharField(max_length=500, null=True, blank=True) buildings = models.ManyToManyField(Building, default=None, blank=True) class Building(models.Model): name = models.CharField(max_length=120, null=True, blank=True) year_of_construction = models.IntegerField(null=True, blank=True) This is what I am doing in my view: class DetailBuildingGroupView(StaffRequiredMixin, DetailView): model = BuildingGroup context_object_name = 'group' queryset = BuildingGroup.objects.all() def get_object(self): id = self.kwargs.get("id") return get_object_or_404(BuildingGroup, id=id) def get_context_data(self, **kwargs): context = super(DetailBuildingGroupView, self).get_context_data(**kwargs) bg = BuildingGroup.objects.filter(id=self.kwargs.get('id')) arr = [] for item in bg: x = item.buildings.values('name', 'net_leased_area') arr.append(x) context['buildings'] = bg return context this gives me back a queryset like this: [<QuerySet [{'name': 'TestBuilding', 'net_leased_area': 1234.0}, {'name': 'Another test building', 'net_leased_area': 2242.0}, {'name': 'Crazy new item', 'net_leased_area': 12.0}]>] this is almost what I want. But now I am trying to turn it into JSON format. I tried various ways like: data = json.loads(serializers.serialize("json", arr)) or like result = list(bg.values('name', 'net_leased_area')) data = (json.dumps(result)) It tells me either that my queryset is not json serializable, or that it has no attribute Meta, or in the last case that it cannot resolve keyword 'name' … -
How can i update another database tables into one existence django project periodically like per day or per week?
Currently one web application django project was used by the client. they want to add another database periodically by per day or a week. How can i update with these database periodically? in python Django MySQL? here we used my SQL. I want merge the another DB with existence django project periodically. -
Return Json array of all data using GET request at /music in Django?
I'm trying to retrieve all the music data. The service should return the JSON array of all the music data by the GET request at /music.The HTTP response code should be 200. The JSON should be sorted in ascending order of music ID. -
Django tells me the table is empty
Hello I have a problem using Django. Basically, I have a table by the name of myTable which has 65 entries. But the problem is in my views.py I do this : from MyProject.models import myTable and then in a function I do this : myTable.objects.all() and using the debugger I got this for myTable.objects.all() : <QuerySet []> So I don't understand at all because my table is not empty. Could you help me please ? Thank you very much ! -
How to query with graphene
I have an query as follows: class MakeObj(graphene.ObjectType): id = graphene.Int() name = graphene.String() class Query(object): makes = graphene.List(MakeObj) def resolve_makes(self, info, **kwargs): makes = get_makes(3) print(makes) return makes In print('makes') the result is fine. I get something as follows: [{'id': 212, 'name': 'ABARTH'}, {'id': 143, 'name': 'AIXAM'}, ....] I want to return that to the frontent where I have next code: const GET_MAKES = gql` query Makes { makes { id name } }`; class Makes extends Component { render() { const {loading, data: {makes}} = this.props; return (...) } } export default withQuery({query: GET_MAKES})(Makes); The withQuery is an high order component and it does what it needs to be done. There is no problems. But in the result, thus this.props.data.makes I get all null values, something as follows: Any idea? -
How to create new database connection in django
I need to create a new database connection(session) to avoid an unexpected commit from a MySql procedure in my transaction. How to set up it in django? I have tried to duplicate the database configuration in setting file. It worked for me but it seems not a good solution. See my code for more detail. @classmethod def get_sequence_no(cls, name='', enable_transaction=False): """ return the sequence no for the given key name """ if enable_transaction: valobj = cls.objects.using('sequence_no').raw("call sp_get_next_id('%s')" % name) return valobj[0].current_val else: valobj = cls.objects.raw("call sp_get_next_id('%s')" % name) return valobj[0].current_val Does anyone know how to use a custom database connection to call the procedure? -
django is not working after enabling https using letsencrypt
My site was working perfect without https i.e) domainname:8001 but after adding the letsencrypt certificate when i tried to access domain name:8001 it's taking to https redirect automatically as coded in the ngnix but the server is not responding. I have tried in http it's working fine. but in https letsencrypt certificate the server is not responding Gunicorn.conf.py proc_name = 'myapp' bind = 'ip:8001' workers = 4 timeout = 1800 graceful_timeout=1800 user = 'root' group = 'www-data' loglevel = 'debug' errorlog = '/home/logs/gunicorn.error.log' accesslog = '/home/logs/gunicorn.access.log' Nignx Configuration: server { server_name domainname.com www.domainname.com; location / { root /var/www/html; index index.html index.htm index.nginx-debian.html; } location /api/ { proxy_pass http://127.0.0.1:8001; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/nuvays.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/nuvays.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.domainname.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = domainname.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name domainname.com www.domainname.com; return 404; # managed by Certbot } Supervisor: [program:app] environment=LANG="en_US.utf8", LC_ALL="en_US.UTF-8", LC_LANG="en_US.UTF-8" command = /usr/local/bin/bin/gunicorn app.app:application -c … -
Prefetch all relationship instances without call .all()
I prefetch_related my objects with the following code: objs = wm.ModelA.objects.prefetch_related( 'ModelB__ModelC') and i want to iterate all ModelB from all objs and i do it with the following way for o in objs: for t in e.ModelB.all(): I noticed that in every iteration of e.ModelB.all() it calls the database. Is there a way to avoid this and bring all MobelB from the begining ? -
how to switch page without refresh page in django?
I have a menu on header and that menu has some option like : about us, store, home, blog I need a way to when user click on each of them, without a refresh or reload page that's template which user click show on a page , how can I do that? -
How to send response to API consumer after finishing working of async task created with celery?
I have a REST API (created using django rest-framework) exposed to USER_1. When USER_1 hits this API, my system creates a async task (created using celery). This task returns some result which I need to return back to USER_1. My question is, how to achieve this without blocking the thread? I tried using .get() method of tasks but it blocks the main thread which defeats the purpose of running tasks asynchronously. Following is structure of my code: views.py class MyAPI(APIView): def post(self, request): task = some_async_task.delay() # Need a way here to get result returned by async task # for now sending some static response return JsonResponse({'status': 'Success'}) tasks.py @app.task def some_async_task(): # some processing that takes few mins result = {'key1': 'value1'} # data I wish to send to USER_1 return result I have searched this already and found that some people are suggesting to use websockets. Honestly, I have no knowledge of websockets. How does this really work? Will USER_1 have to send me request through websockets? Or is it something that I need to implement at just my side? Or do we both have to implement this? Any help and guidance would be appreciated. -
Define formula on django admin
is there anyway or a library that can help me so that the admin can define a formula. For example F = a*b + c and the admin can add operations easily. I know this requires customizing the admin template but any idea could help -
ListView show data according to the signed in User
I know this question has already been asked but the methods mentioned do not work for me. I'm getting this error Traceback: File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\views\generic\base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\views\generic\base.py" in dispatch 88. return handler(request, *args, **kwargs) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\views\generic\edit.py" in post 217. return super(BaseCreateView, self).post(request, *args, **kwargs) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\views\generic\edit.py" in post 183. return self.form_valid(form) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\views\generic\edit.py" in form_valid 162. self.object = form.save() File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\forms\models.py" in save 468. self.instance.save() File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\db\models\base.py" in save 808. force_update=force_update, update_fields=update_fields) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\db\models\base.py" in save_base 838. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\db\models\base.py" in _save_table 924. result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\db\models\base.py" in _do_insert 963. using=using, raw=raw) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\db\models\manager.py" in manager_method 85. return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\db\models\query.py" in _insert 1079. return query.get_compiler(using=using).execute_sql(return_id) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\db\models\sql\compiler.py" in execute_sql 1112. cursor.execute(sql, params) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\db\backends\utils.py" in execute 79. return super(CursorDebugWrapper, self).execute(sql, params) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\db\backends\utils.py" in execute 64. return self.cursor.execute(sql, params) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\db\utils.py" in exit 94. six.reraise(dj_exc_type, dj_exc_value, traceback) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\db\backends\utils.py" in execute 64. return self.cursor.execute(sql, params) File "C:\Users\BITSWI~1\Desktop\Maala\Maala\lib\site-packages\django\db\backends\sqlite3\base.py" in execute 328. return Database.Cursor.execute(self, … -
Django Management Command pytest assert_called_with - Not Called
Django management command: my_custom_command.py from django.core.management.base import BaseCommand from services.external import ExternalApi class Command(BaseCommand): def handle(self, *args, **options): api = ExternalApi() api.my_custom_method("param") Test Code: from django.core.management import call_command from myapp.management.commands import my_custom_command def test_custom_command(mocker): mocker.patch.object(my_custom_command, 'ExternalApi') call_command('my_custom_command') my_custom_command.ExternalApi.my_custom_method.assert_called_with('param') Result: def test_custom_command(mocker): mocker.patch.object(my_custom_command, 'ExternalApi') call_command('my_custom_command') > my_custom_command.ExternalApi.my_custom_method.assert_called_with('param') E AssertionError: Expected call: my_custom_method('param') E Not called Though the my_custom_method has been invoked, the test couldn't find the method call. It seems to be the context is missing. Could you please help? -
How to return function result in GraphQL
I'm using React, Apollo and GraphQL at the frontend and Django, Python and Graphene at the backend. I want to implement search_bar and when user click on search button I want to execute GraphQL query with the user input. At the backend I want to grap that string and I want to pass it to an function and then returned result from the function I want to pass back to the frontend. I have code as follows: FRONTEND export const GET_RESULTS = gql` query SearchVinResults($vin: String!){ searchVinResults(vin: $vin) { id label url } }`; class VinSearch extends Component { onVinSearch(e) { e.preventDefault(); const {value, client: {query}} = this.props; query({query: GET_RESULTS, variables: { vin: value }}); } render() { const {value, clearSearch, onChange} = this.props; return ( <SearchField onChange={e => onChange(e)} clearSearch={() => clearSearch()} value={value} clearIcon="fal fa-times" placeholder="Search VIN" withButton={true} buttonStyles={{borderLeftWidth: 0}} onClick={e => this.onVinSearch(e)} /> ); } } export default withApollo(VinSearch); Backend class Query(object): search_vin_results = ???? # What do I need to do here def resolve_search_vin_results(self, info, **kwargs): # Here I want to do something like vin = info['vin'] results = get_vins(vin) return results Any idea? -
Why django 2.2 URLs always ends with "/" otherwise not working and gives 404 page not found error
why "blog/" works but "blog" not working ? why need to add "/" at URL end ?