Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django login with custom form template
I'm using the Django authentication with my login form in my template, after i pressed the login button on the form the page refresh but doesn't log me in and doesn't show the {{context}} error in the template. My view: > def login_view(request): > if request.method == 'POST': > all_categories = Categories.objects.all() > all_websites = Website.objects.all() > all_discounts = Discount.objects.order_by('-id') > 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) > return redirect('/',categories=all_categories,websites=all_websites,discounts=all_discounts) > else: > context = 'wrong username or password' > all_categories = Categories.objects.all() > all_websites = Website.objects.all() > all_discounts = Discount.objects.order_by('-id') > return redirect('/',categories=all_categories,websites=all_websites,discounts=all_discounts,context=context) My form (header.html) <div class="col-md-3 top-info-cart text-right mt-lg-4"> {% if user.is_authenticated %} <p>Welcome, {{ user.username }}.</p> <p><a href="{% url 'frontend:logout' %}">logout</a></p> {% else %} <ul class="cart-inner-info"> <li class="button-log"> <a class="btn-open" href="#"> <span class="fa fa-user" aria-hidden="true"></span> </a> </li> </ul> <p>{{context}}</p> {% endif %} <!----> <div class="overlay-login text-left"> <button type="button" class="overlay-close1"> <i class="fa fa-times" aria-hidden="true"></i> </button> <div class="wrap"> <h5 class="text-center mb-4">Login Now</h5> <div class="login p-5 bg-dark mx-auto mw-100"> <form action="{% url 'frontend:login' %}" method="post"> {% csrf_token %} <div class="form-group"> <label class="mb-2">User name</label> <input type="text" name="username" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> <small id="emailHelp" class="form-text text-muted">We'll … -
Celery connecting to rabbitmq-server instead of redis-server
I have a Django application which I want to configure it celery to run background tasks. Packages: celery==4.2.1 Django==2.1.3 Python==3.5 Configuration of celery in settings.py file is: CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Kolkata' CELERY_BEAT_SCHEDULE = { 'task-number-one': { 'task': 'app.tasks.task_number_one', 'schedule': crontab(minute='*/1'), }, } And celery.py file: from __future__ import absolute_import, unicode_literals import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings.prod') app = Celery('niftytrader_temp') # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings') # Load task modules from all registered Django app configs. app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) When I run : celery -A niftytrader_temp worker -l info -B -E It points to rabmmitmq server, instead it should point to redis-server, shown below: -------------- celery@user-desktop v4.2.1 (windowlicker) ---- **** ----- --- * *** * -- Linux-4.15.0-39-generic-x86_64-with-Ubuntu-18.04-bionic 2018-11-21 12:04:51 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: project:0x7f8b80f78d30 - ** ---------- .> … -
What is the proper way to process the user-trigger events in Django?
For example, I have a blog based on Django and I already have several functions for users: login、edit_profile、share. But now I need to implement a mission system. User logins, reward 10 score per day User completes his profile, reward 20 score User shares my blogs, reward 30 score I don't want to mix reward code with normal functions code. So I decide to use message queue. Pseudo code may look like: @login_required def edit_profile(request): user = request.user nickname = ... desc = ... user.save(...) action.send(sender='edit_profile', payload={'user_id': user.id}) return Response(...) And the reward can subscribe this action @receiver('edit_profile') def edit_profile_reward(payload): user_id = payload['user_id'] user = User.objects.get(id=user_id) mission, created = Mission.objects.get_or_create(user=user, type='complete_profile') if created: user.score += 20 user.save() But I don't know if this is the right way. If so, what message queue should I use? django-channel / django-q or something else? If not, what is the best practice? -
How Count() woks?
In the book that I am, reading so as to count the number of tags in common between multiple posts the Count from django.db.models is used. For tags the taggit is used. But I am quite confused how this functionality is working post_tags_ids = post.tags.values_list('id', flat=True) similar_posts =Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id) similar_posts = similar_posts.annotate(same_tags=Count('tags')).order_by('-same_tags', '-publish')[:4] In my case, I have several posts and each has two tags. Each post shares only one tag with other posts. I am getting the list of the ids of the tags that the post that I am interested in contains. Then according to that list, I am filtering out other posts. Then I am adding same_tags parameter for all the posts, counting the tags they have. My confusion is here, as I said I have two tags in each post but magicaly here same_tag is counting one which is the number of tags that post shares with the post of my interest. How this is happening? Here is my test in the shell >>> posts [<Post: This is the other one >, <Post: Some content >, <Post: Other Post>,<Post: Temurs learning curv>] >>> post = Post.objects.get(pk=1) >>> post_tags_ids = post.tags.values_list('id', flat=True) >>> post_tags_ids [2, 3] similar_posts = … -
how to stop routers from creating unwanted urls in Django RestFrameWork
I am using DefaultRouters in my project for creating urls. my question is how can i prevent routers from creating some urls for certain urls. eg: i have a url 127.0.0.1:8000/api/users/ which returns a list view, but at the same time router is also creating urls like 127.0.0.1:8000/api/users\.(?P<format>[a-z0-9]+)/?$ which i do not want to be there. here is my files views.py class UserAuthAPIView(ModelViewSet): queryset = UserModel.objects.all() serializer_class = ListViewSerializer urls.py from rest_framework_mongoengine import routers as merouters from UserAPI.api.views import UserAuthAPIView #UpdatePasswordSerializer merouter = merouters.DefaultRouter() merouter.register(r'users', UserAuthAPIView, base_name='user') urlpatterns = [] urlpatterns += merouter.urls -
django docker-compose deleting data from mongo database when i am doing "docker-compose down" and again"up"
DockerFile: FROM python:3.6 WORKDIR /usr/src/jobsterapi COPY ./ ./ RUN pip install -r requirements.txt CMD ["/bin/bash"] docker-compose.yml version: "3" services: jobster_api: container_name: jobster build: ./ # command: python manage.py runserver 0.0.0.0:8000 command: "bash -c 'python src/manage.py makemigrations --no-input && python src/manage.py migrate --no-input && python src/manage.py runserver 0.0.0.0:8000'" working_dir: /usr/src/jobster_api environment: REDIS_URI: redis://redis:6379 MONGO_URI: mongodb://jobster:27017 ports: - "8000:8000" volumes: - ./:/usr/src/jobster_api links: - redis - elasticsearch - mongo #redis redis: image: redis environment: - ALLOW_EMPTY_PASSWORD=yes ports: - "6379:6379" elasticsearch: image: docker.elastic.co/elasticsearch/elasticsearch:6.5.0 ports: - "9200:9200" - "9300:9300" mongo: image: mongo ports: - "27017:27017" I have done setup django with mongodb inside docker using following docker-compose command. it is working fine every thing. but when i am adding any records using "docker exec -it 'img id' /bin/bash" it is inserting data(i tried creating superuser for django admin panel). but, when i am again making it "docker-compose up" after "docker-compose down" it is deleting all data from database showing empty records. so i am not able to access admin panel also for next timeself. Please have a look......... -
How can I use aggregate sum with division?
I want to get average of the total within the past 3 months. I have an object called 'Book' and attribute 'total'. I need to sum up the total and divide by 3 to get the avg for one month. Here is my code: past_3_month_avg = Book.objects.filter(trandate_b__range=(past_3_month_first_day,current_month_first_day)).aggregate(Sum('total')) I have tried: past_3_month_avg = Book.objects.filter(trandate_b__range=(past_3_month_first_day,current_month_first_day)).aggregate(Sum('total')/3) It return error: File "C:\Python\Python36\lib\site-packages\django\db\models\query.py" in aggregate 360. arg.default_alias During handling of the above exception ('CombinedExpression' object has no attribute 'default_alias'), another exception occurred: File "C:\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\customers\views.py" in Summary 222. past_3_month_avg = Book..objects.filter(trandate_b__range=(past_3_month_first_day,current_month_first_day)).aggregate(Sum('total')/3) File "C:\Python\Python36\lib\site-packages\django\db\models\query.py" in aggregate 362. raise TypeError("Complex aggregates require an alias") Exception Type: TypeError at /summary/ Exception Value: Complex aggregates require an alias -
which more on security; MySQL or PostgreSQL [on hold]
Hi I'm new to web programming, and I'm working on a website with Django web framework. But now I want to switch my SQLite database out and replace with either MySQL or PostgreSQL, I been googling on both database management language and seems to work well on Django but, the important is security; which language less secure??? -
If-statement too nested?
I use the following code to check if the ticket should contain a discount or not. There are now three if-statements and I wonder if there is a better way to not make it less nested? ticket_price = current_ticket.display_price discount_code_session = request.session.get(request.event.discount_code_cookie(), None) if discount_code_session: discount_code = Discount.objects.filter( code=discount_code_session, event=request.event.pk ).first() # Make sure discount_code exists if discount_code: discounted_tickets = discount_code.tickets.all() # Why not discounted_tickets: If discounted_tickets empty, then the # discount code is valid for all tickets. if not discounted_tickets or current_ticket in discounted_tickets: discounted_price, original_price = ( discount_code.calculate_discounted_value(ticket_price) ) ticket_price_dict = { 'original_price': original_price, 'discounted_price': discounted_price, } return ticket_price_dict return ticket_price -
Django Resize image in Forms
I'm using python 3.6 and Django 2.0. I have a square image that I want uploaded to a model. I currently have an image field in a model that I can upload. avatar = models.ImageField(path_and_rename, max_length=255, blank=True I want to resize whatever square image is uploaded to be 750 by 750. I thought of a way to do it, but I don't think I'm saving it as the right type as it is giving me an error. 'Image' object has no attribute '_committed' How can I resize my square image to meet the new dimensions that I need. My code (leaving out validation to make it simpler): forms.py def clean_avatar(self): avatar = self.cleaned_data['avatar'] try: print(len(avatar)) w, h = get_image_dimensions(avatar) max_width = max_height = 750 image = Image.open(avatar) resized_image = image.resize((max_width,max_height), Image.ANTIALIAS) print(type(avatar)) print(type(image)) print(type(resized_image)) return resized_image except ... the output of the above is <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> <class 'PIL.JpegImagePlugin.JpegImageFile'> <class 'PIL.Image.Image'> if I return avatar it works, but it doesnt' work when I return resized_image. How can I make the datatype of resized_image that of avatar? Full error message: File "C:\myapp\lib\site-packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\myapp\lib\site-packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\myapp\lib\site-packages\django\core\handlers\base.py" in _get_response 126. … -
Creating another virtualenv for a new Django project
I'm learning Django and Python. If it is right that I understood, I need to create a new virtualenv per Django project. python django: create a new virtualenv for each django project? I installed virtualenv when I was following a Django tutorial before. I want to create an application to practice. so I'm trying to install a new virtualenv. However powershell shows me this. virtualenv installation error? How can I install another virtualenv in this case? could you please give me an advice or link to solve this problem. Thank you. -
How to attach graph-tool to Django using Docker
I need to use some graph-tool calculations in my Django project. So I started with docker pull tiagopeixoto/graph-tool and then added it to my Docker-compose file: services: version: '3' services: db: image: postgres graph-tool: build: . image: dcagatay/graph-tool web: build: . command: python3 manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db - graph-tool When I up my docker-compose I got a line: project_graph-tool_1_87e2d144b651 exited with code 0 And finally when my Django projects starts I can not import modules from graph-tool, like: from graph_tool.all import * If I try work directly in this docker image using: docker run -it -u user -w /home/user tiagopeixoto/graph-tool ipython everything goes fine. What am I doing wrong and how can I fix it and finally attach graph-tool to Django? Thanks! -
Paypal sandbox ipn subscription bug
I am implementing subscription with Paypal IPN and Django. The transaction process was fine till 11/16/2018 around 3PM. After that, the transaction history on Paypal customer account went buggy. I tried to pay $1 to subscribe twice but no records is shown on the following page. enter image description here However, if I go to https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_manage-paylist, I can see those records. And the facilitator account also has the similar issue, no records show up on the history on the main page but those records can be seen on the subscription management page. I used two accounts to test it. Same issue. Any idea what is going on? -
Django: required field even with true=blank on form submision
I've a form that has a field 'instrucciones' that should be optional to complete. I've tried to modified it in the model and put it as a blank field, null true, and even use a default (''). instrucciones = models.CharField(max_length=200, blank=True, null=True, default='') However, in submition I'm ask to complete this field. Why? class TamaniosCantidades(models.Model): TAMANIOS = (('2x2', '2" x 2"',), ('3x3', '3" x 3"',), ('4x4', '4" x 4"',), ('5x5', '5" x 5"',)) CANTIDADES = (('50', '50',), ('100', '100',), ('150', '150',)) # usuario = models.ForeignKey(User, on_delete=models.DO_NOTHING) tamanios = models.CharField(max_length=10, choices=TAMANIOS) cantidades = models.CharField(max_length=10, choices=CANTIDADES) imagenes = models.FileField(upload_to='imagenes/', null=True) instrucciones = models.CharField(max_length=200, blank=True, null=True, default='') # uploaded_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.tamanios forms.py # Declare Forms class StepOneForm(forms.Form): tamanios = forms.ChoiceField(choices=TAMANIOS, widget=forms.RadioSelect(), label='Selecciona un tamaño') cantidades = forms.ChoiceField(choices=CANTIDADES, widget=forms.RadioSelect(), label='Selecciona la cantidad') class StepThreeForm(forms.ModelForm): instrucciones = forms.CharField(widget=forms.Textarea) class Meta: model = TamaniosCantidades fields = ('imagenes', 'instrucciones') html: {% csrf_token %} <div class="form-group"> {{ form.imagenes|as_crispy_field }} <div id="instrucciones-adicionales" style="display: none"> <p class="bold-font"> Instrucciones adicionales (opcional):</p> {{ form.instrucciones|as_crispy_field }} </div> </div> </br> </br> <p>O, sáltate este paso y envía tu arte por correo electrónico</p> <button type="submit" class="btn btn-naranja text-white btn-block">Continuar </button> </form> -
Access to the camera from the system the application is running on
I am building a web application with django and opencv for computer vision. In the web application there exists a button which when pressed starts the web cam of my computer. The problem is when i host the web application using my IP and access the application with a different computer and press the button, The webcam in my computer start. I knew the problem lied in this line of code cam = cv2.VideoCapture(0) I looked online and found this post , which asks me to use javascript to access the webcam. Is that the best option available or can I somehow change that line of opencv code to access the camera in the system the application is running on? If there is no better way to do it than javascript, then I would also like to know once I access the webcam and display the feed onto the screen, how do I link the rest of the python code like the face detectors and classifiers to the javascript code? I have just started getting my hands dirty with python and i still have a lot to learn. Thanks in advance -
PLC to Server to Web
First, thank you for reading this second, I'm a new to all this as i'm fresh out colleges and I'm tasked with developing this project that allows, a plc to read the input (analogue data) at the factory and send its data to the server(A PC) by wireless, at the factory. The Server will then upload the data onto a webpage; where it can be view anywhere, mobile or computer. Now questions how do I let server read plc data and upload to the webpage in real time? I'm using MITSUBISHI PLC FX3G-14MR/ES-A and The website I'm doing is a Django framework/python The Server Database I'm considering between this three: PostgreSQL MySQL MongoDB But which more scalable and had strong security Are there tips, any recommendations? or website where I can start? -
Filtering Django Queryset Based on Presence of String
I have a model which renders a json file in views.py: def bill_sum(request): data = Summary.objects.values('title','summary','summary_text') return render(request,'billsummary.html',context={'data':data}) Is it possible to filter the summary_text object query by looking up a specific string which I would pass in from urls.py? Something like using from django.db.models import Q Summary.objects.values('title;'summary',Q('summary_text'__contains=someword),...) -
How to send email with django "Rest Framwork"?
I'm using small Rest api project and it works fantastic. But somehow i have to make send email function in there. so i added email config in settings.py like that // settings.py # SMTP Mail service with decouple EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = "smtp.gmail.com" EMAIL_HOST_USER = config('EM_ACCOUNT') EMAIL_HOST_PASSWORD = config('EM_PASSWORD') EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = EMAIL_HOST_USER //views.py from rest_framework import viewsets from consult.models import Consult from consult.serializers import ConsultSerializer from django.core.mail import EmailMessage class ConsultViewSet(viewsets.ModelViewSet): queryset = Consult.objects.all() serializer_class = ConsultSerializer def send_email(request): email = EmailMessage( 'Title', (ConsultSerializer.name, ConsultSerializer.email, ConsultSerializer.phone), 'my-email', ['my-receive-email'] ) email.attach_file(ConsultSerializer.file) email.send() // models.py from django.db import models # Create your models here. class Consult(models.Model): name = models.CharField(max_length=16) position = models.CharField(max_length=16, null=True) group = models.CharField(max_length=50) email = models.CharField(max_length=50, null=True) phone = models.CharField(max_length=14) describe = models.TextField(blank=True, null=True) file = models.FileField(blank=True, null=True) create_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) class Meta: db_table = 'Consult' // serializers.py from rest_framework import serializers from .models import Consult class ConsultSerializer(serializers.ModelSerializer): class Meta: model = Consult fields = ('id', 'name', 'position', 'group', 'email', 'phone', 'describe', 'file', 'create_date') Yup. that is all of my codes. And i setted send_mail function in views. Honestly I want automatic send mail function when the consult data … -
Changing a form field's 'required' property with save_model in Django admin
I have tried all the different examples and methods I could find on Stack Overflow for this, and for whatever reason, can get this to work properly. So in my admin.py I have a UserForm and and UserAdmin. Based on the condition where a boolean is checked within the form, I want to change the 'required' attribute on a few different form fields to 'false' so I can effectively save. I've used a few different print statements to ascertain that the 'required' is in fact getting changed to false when the condition is met, however, when I try and save, it won't let me as the fields highlight and say they're still required. It is almost like the save_model doesn't care how I edit the form, that the old form and its 'required' attributes are overriding my changes. Thanks for any help! admin.py class UserAdmin(admin.ModelAdmin): model = Order form = UserForm def save_model(self, request, obj, form, change): if obj.pickup_only == 1: form.fields['address'].required = False form.fields['city'].required = False form.fields['state'].required = False form.fields['zipcode'].required = False return super(UserAdmin, self).save_model(request, obj, form, change) -
How to use posgresql 'interval' in Django?
Here is my PostgreSQL statement. select round(sum("amount") filter(where "date">=now()-interval '12 months')/12,0) as avg_12month from "amountTab" How to use this in Django? I have an object called 'Devc', with attribute 'date'. I want to get the sum of the specific data within past 12 months, not past 365 days. -
Add a dynamic number of fields to Django admin form
I have 3 Models "Configuration", "Process", and "ProcessConfiguration" as defined below: class Configuration(models.Model): name = models.CharField(max_length=MAX_CONFIGURATION_NAME_LEN, unique=True, db_index=True) description = models.TextField(blank=True) validation = models.CharField(max_length=MAX_CONFIGURATION_VALIDATION_LEN, blank=True) entity = models.CharField(max_length=MAX_CONFIGURATION_ENTITY_LEN, blank=False) is_customer_visible = models.BooleanField(default=False, editable=True) class ProcessConfiguration(models.Model): process = models.ForeignKey(Process, on_delete=models.CASCADE, db_index=True) configuration = models.ForeignKey(Configuration, on_delete=models.CASCADE, db_index=True) value = models.TextField() created = models.DateTimeField(editable=False, auto_now_add=True, db_index=True) def __str__(self): return self.process.name + ": " + self.configuration.name + " = " + self.value[:80] class Meta: unique_together = ('process', 'configuration') class Process(models.Model): name = models.CharField(max_length=MAX_PROCESS_NAME_LEN) What I am trying to do is to add a new CharFeild to the Process admin form for each of the Configuration objects that have a particular entity flag set. I thought I would be able to do this how I have added other fields to forms, but within a loop. class ProcessCreateForm(forms.ModelForm): test_above = forms.CharField() def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) extented_configurations = Configuration.objects.filter(entity='proc', is_customer_visible=True) for config_item in extented_configurations: kwargs = { 'label': "123", 'required': False } field_class = forms.CharField self.fields[config_item.name] = field_class(**kwargs) When I print out the fields at the end of the init, I can see that the new fields have been added, however when I load the page I can only see the "test_above" field. The end … -
django rest serialize a string when model object is not defined
having trouble serializer a string during a try/except statement. here i have a endpoint that calls another function refund the response i get back from that function i'm trying to serialize. class RefundOrder(APIView): def post(self, request, **kwargs): print('test') body_unicode = request.body.decode('utf-8') body_data = json.loads(body_unicode) amount = body_data['amount'] tenant = get_object_or_404(Tenant, pk=kwargs['tenant_id']) refund = SquareGateway(tenant).refund(amount) serializer = RefundSerializer(refund) return Response(serializer.data) this is the function that gets called in the post endpoint. i added it in a try statement to handle the errors from square api. if the api call fails, i want to return an error if their is one, else serialize that data. def refund(self, order, amount, reason): try: response = self.client.transaction().create_refund(stuff) refund = Refund( order=order, amount=response.refund.amount_money.amount, ) refund.save() return refund except ApiException as e: return json.loads(e.body)['errors'][0]['detail'] this is the the Refundserialize class RefundSerializer(serializers.ModelSerializer): class Meta: model = Refund fields = ('id', 'amount') -
Creating a simple webpage with Python, where template content is populated from a database (or a pandas dataframe) based on query
I use python mainly for data analysis, so I'm pretty used to pandas. But apart from basic HTML, I've little experience with web development. For work I want to make a very simple webpage that, based on the address/query, populates a template page with info from an SQL database (even if it has to be in a dataframe or CSV first that's fine for now). I've done searches but I just don't know the keywords to ask (hence sorry if this a duplicate or the title isn't as clear as it could be). What I'm imagining (most simple example, excuse my lack of knowledge here!). Example dataframe: import pandas as pd df = pd.DataFrame(index=[1,2,3], columns=["Header","Body"], data=[["a","b"],["c","d"],["e","f"]]) Out[1]: Header Body 1 a b 2 c d 3 e f User puts in page, referencing the index 2: "example.com/database.html?id=2" # Or whatever the syntax is. Output-page: (Since id=2, takes data row data from index = 2, so "c" and "d") <html><body> Header<br> c<p> Body<br> d<p> </body></html> It should be pretty simple right? But where do I start? Which Python library? I hear about Django and Flask, but are they? Is there an example I could follow? And lastly, how does the syntax … -
Creating serializer to display correct data
I have 4 models. User, Question, Choice, and Voting. This is basically a polls app I'm trying to create. A question can have many choices. The Voting model tracks what each user chose as their answer. What I'd like to do is retrieve all the questions and also check what choice the logged in user selected for each question. Here's the models: class Question(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) status = models.CharField(max_length=200) total_votes = models.IntegerField(default=0) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice = models.CharField(max_length=120) vote_count = models.IntegerField(default=0) class Voting(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) choice = models.ForeignKey(Choice, on_delete=models.CASCADE) Here's how I want the data displayed: { user: 2 status: "Hello" total_votes: 101 choices: [ { "id": 2, "choice": "first choice", "vote_count": 31, "question": 3 }, { "id": 4, "choice": "second choice", "vote_count": 70, "question": 3 } ], choice_selected: 2 } In the data above, the logged in user selected choice 2 in this specific question. class ChoiceSerializer(serializers.ModelSerializer): class Meta: model = Choice fields = '__all__' class QuestionSerializer(serializers.ModelSerializer): choices = ChoiceSerializer(source='choice_set', many=True) class Meta: model = Question fields = '__all__' class GetProfileQuestions(ListAPIView): serializer_class = QuestionSerializer def get_queryset(self): return Question.objects.all() This query successfully prints out each question and its choices. However, how do I … -
Python JOB in separated project
I have a Django Project with some CRUD pages. Now i need create a JOB to make some task once per minute. I think about two solutions but i would like to know which should be better approach to follow Python Best Practices: 1- Create a job.py inside my django project and call a start() method when urls.py is called, because i need initialize this job.py in some moment. 2- Create a job.py in separated project and run "python job.py". For me, is better create a separated project and run "python job.py" because my job don't depends on django project. But i really don't know if a good choice in python world.