Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 ? -
How can i use prefetch_related on nested serializer
i have a ProductSerializer and this serializer has photos on another model and serializer. So i want to prefetch photos in ProductSerializer. But i use to ProductSerializer in the a few serializer. I can't override queryset in Views. class RentalProductSerializer(serializers.ModelSerializer): photos = RentalProductPhotoSerializer(read_only=True, many=True) class Meta: model = Product list_serializer_class = ProductListSerializer fields = ['categories', 'stock_code', 'description', 'brand', 'model_name', 'photos', 'url'] class RentalOfferLineSerializer(serializers.ModelSerializer): product_detail = RentalProductSerializer(read_only=True, many=False, source='product') class Meta: model = RentalOfferLine fields = ( 'id', 'product', 'product_detail', 'currency', 'rent_price', 'quantity', ) -
Fill data into Model Form Django and pass id paramater in URL Django
I'm trying fill data into model form and load pages with information field of object. However, I get some error and I don't know fix views.py def profile(request, id): user = get_object_or_404(User, id=id) user_info = get_object_or_404(UserInfor, user_id=user.id) user_form = UserForm(instance=user) profile_form = ProfileForm(instance=user_info) return render(request, 'pages/profile.html', {'user': user_form, 'user_info': profile_form}) urls.py path('profile/id=<int:id>/', views.profile, name='profile') profile.html <form class="form-horizontal" name="form" method="post" action="{% url 'profile' %}"> Error I got NoReverseMatch at /profile/id=2/ Reverse for 'profile' with no arguments not found. 1 pattern(s) tried: ['profile\/id\=(?P[0-9]+)\/$'] Request Method: GET Request URL: http://127.0.0.1:8000/profile/id%3D2/ Django Version: 2.2.1 Exception Type: NoReverseMatch Exception Value: Reverse for 'profile' with no arguments not found. 1 pattern(s) tried: ['profile\/id\=(?P[0-9]+)\/$'] Exception Location: F:\FTEL_CSOC\env\lib\site- packages\django\urls\resolvers.py in _reverse_with_prefix, line 668 Python Executable: F:\FTEL_CSOC\env\Scripts\python.exe Python Path: ['F:\FTEL_CSOC\webping', 'F:\FTEL_CSOC\webping', 'F:\FTEL_CSOC\webping', 'C:\Program Files\JetBrains\PyCharm 2019.1.1\helpers\pycharm_display', 'F:\FTEL_CSOC\env\Scripts\python36.zip', 'C:\Users\vuthe\AppData\Local\Programs\Python\Python36\DLLs', 'C:\Users\vuthe\AppData\Local\Programs\Python\Python36\lib', 'C:\Users\vuthe\AppData\Local\Programs\Python\Python36', 'F:\FTEL_CSOC\env', 'F:\FTEL_CSOC\env\lib\site-packages', 'F:\FTEL_CSOC\env\lib\site-packages\setuptools-40.8.0-py3.6.egg', 'C:\Program Files\JetBrains\PyCharm ' '2019.1.1\helpers\pycharm_matplotlib_backend'] Server time: Mon, 24 Jun 2019 07:29:28 +0000 -
How can i get value from database in table radio button in ajax ,json and django
how can i get value from database (the value is T and F) in table radio button .the radio button change according to the database -
django template not show ForeignKey items
im new to django im having problem with my foreignkey items not displaying hope you can help me... thank you. here's my models.py class Reporter(models.Model): name = models.CharField(max_length=20) address = models.CharField(max_length=30) def __str__(self): return self.name class News(models.Model): headline = models.CharField(max_length=50) reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) def __str__(self): return self.headline and my views.py def index(request): reportlist = Reporter.objects.all() context = { 'reportlist': reportlist } return render(request, 'index.html', context) and my template {% block content %} {% for r in reportlist %} <p>{{r.name}}</p> {% for items in r.item_set.all%} <p>{{items.headline}}</p> {%endfor%} <br/> {%endfor%} {% endblock %} -
Not Found: /en/
Not Found: /en/ Error in Django CMS **Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/en/ Raised by: cms.views.details** Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: '''''''''''''''''''''''''''''''' ^media/(?P<path>.*)$ ^static\/(?P<path>.*)$ ^sitemap\.xml$ ^en/ ^admin/ ^en/ ^ ^cms_login/$ [name='cms_login'] ^en/ ^ ^cms_wizard/ ^en/ ^ ^(?P<slug>[0-9A-Za-z-_.//]+)/$ [name='pages-details-by-slug'] ^en/ ^ ^$ [name='pages-root'] The current path, /en/, didn't match any of these. -
How to give different feedback when is_active is false?
I am implementing token verification for signing up using Django. I set is_active=False as default and change it to True when the user click a verification link sent to their email. But before the user click the link, I wanted to prepare for the case that the user attempt to log in. Because the user did not click the link and is_active did not turn to True, it will give an invalid credential error. However, the thing is I want to differentiate the case who did not complete the verification process from those who made an attempt to log in with wrong username or password. So my question boils down to: How to give different feedback when is_active is False from when username or password were incorrect? How can I customize jwt-graphene-django to return the customized error? This is the only customization code I found for jwt-graphene-django class ObtainJSONWebToken(graphql_jwt.JSONWebTokenMutation): user = graphene.Field(UserType) @classmethod def resolve(cls, root, info, **kwargs): return cls(user=info.context.user) -
styling django forms using reactjs
I learnt about django-forms, and I wanna create a form which looks nice, styling with css and bootstrap and html. but I found that out that I can't do it clean (like creating separate css sheet for styling) and I have to do it through python code which is doesn't look good. is there any way to do this? if I try to handle the whole frontend, do I still need to set some styles through python in backend including django forms? I'm sorry if it is a dumb question but I'm new to reactjs(actually I didn't learn it yet) and I have just a little experience in django.