Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a new file in heroku using the frontend of the website?
I am not sure whether the title of the question is informative, that's why I am going to explain what I want to do. I deployed this website in heroku. http://tkastrodb.herokuapp.com/ Users can make selections then if they press the Start button, the calculation process starts. There's a worker that handles the shared tasks for calculations. It works perfectly fine. However at the end of the calculation, the results are put in a spreadsheet file named as observed_values.xlsx. And this file should be downloadable. So in the beginning there is any file called observed_values.xlsx, but after the calculation is completed, a new file should be created in heroku, so a window could be popped up to download this file, how can I do that? -
what is the best approach to implement my custom queryset, and api reponse on error?
I'm doing a university project that requires me to implement a Web App using an API as backend and I've decided to use DRF to do it but I'm having some troubles right now. I'm trying to override the get_queryset method in Viewset to only show the response with the following data _id, _name, and data where data is a nested serialize however, I want to implement the following features implement custom ordering handle responses custom ordering by given arraylist from django.db.models import Case, When pk_list = [10, 2, 1] preserved = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(pk_list)]) queryset = MyModel.objects.filter(pk__in=pk_list).order_by(preserved) viewset class ServiceViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): queryset = MyModelB.objects.all() serializer_class = ServiceSerializer def get_queryset(self): domain = self.request.query_params.get('domain', None) domain_id = MyModelA.objects.filter(name=domain).first() if domain is not None: self.queryset = self.queryset.filter(domain=domain_id) return self.queryset serializer class ServiceSerializer(serializers.ModelSerializer): data = BSerializer(source='mymodelc_set',many=True) class Meta: model = MyModelB fields = ('_id','_name','data',) -
js sum of value of select field by row group
My template: <form method="post">{% csrf_token %} <div class="row"> <div class="col-md-8"> <div class="row"> <div class="col"> <h7 style="font-weight:bold;">Market trend</h7> </div> <div class="center"> <input class="speech-bubble" value="0" id="marklRate" name="markRate"> </div> </div> <div class="form-row border"> <div class="form-group col-md-2 mb-0" name="market-1"> {{ form.cycleMarket|as_crispy_field }} </div> <div class="form-group col-md-2 mb-0" name="market-2"> {{ form.news|as_crispy_field }} </div> <div class="form-group col-md-3 mb-0" name="market-3"> {{ form.managementPostion|as_crispy_field }} </div> <div class="form-group col-md-2 mb-0" name="market-4"> {{ form.short|as_crispy_field }} </div> </div> <br> <div class="row"> <div class="col"> <h7 style="font-weight:bold;">Analysts advice</h7> </div> <div class="center"> <input class="speech-bubble" value="0" id="analRate" name="analRate"> </div> </div> <div class="form-row border" > <div class="form-group col-md-3 mb-0" target="_blank" rel="noopener noreferrer" name="analyst-1"> {{ form.BARCHART_analysts|as_crispy_field }} <a href="https://www.barchart.com/stocks/quotes/{{ stck.codeBarchart }}/overview" target="_blank" rel="noopener noreferrer">Go to Barchart</a> </div> <div class="form-group col-md-4 mb-0" target="_blank" rel="noopener noreferrer" name="analyst-2"> {{ form.TRADINGVIEW_analysts|as_crispy_field }} <a href="https://www.tradingview.com/symbols/{{ stck.codeTradingviews }}" target="_blank" rel="noopener noreferrer">Go to Tradview</a> </div> <div class="form-group col-md-3 mb-0" target="_blank" rel="noopener noreferrer" name="analyst-3"> {{ form.INVESTING_analysts|as_crispy_field }} <a href="https://www.investing.com/{{ stck.codeInvesting }}" target="_blank" rel="noopener noreferrer">Go to Investing</a> </div> </div> <br> On loading page, I want to calculate each speech-bubble value . calculation is some of select fields value which are in the same class row. For this example : speech-bubble id mark rate should be the some of market-1, market-2, market3, market-4 values. Code should be … -
How I can increase the likes number by +1 when hit the button in Django using Ajax
I hade created the ajax and it's work I got difficult to increase the number of likes +1 when I click the button and change the color to blue and decrement-1 when I hate the like button again and change the color my html template <form method="POST" action="{% url 'video:like' video.pk %}" id="my-like-form"> {% csrf_token %} <input type="hidden" class="likin" name="next" value="{{ request.path }}"> <button class="remove-default-btn" type="submit" id="openPopup" class="remove-default-btn like-btn{{ request.path }}" style="border: none; "> <i class="fa fa-thumbs-up" aria-hidden="true"><span>{{ video.likes.all.count }}</span></i> Like </button> </form> The JavaScript (Ajax) $("#my-like-form").submit(function(e){ e.preventDefault(); let form = $(this); let url = form.attr("action"); const likes = $(this).find("button[class*=like-btn] span").text(); const trimCount = parseInt(likes) console.log(trimCount) $.ajax({ type: "POST", url: url, data: form.serialize(), dataType: "json", success: function(response) { selector = document.getElementsByName(response.next); if(response.liked==true){ $('.like-btn{{ request.path }}').css("color","blue"); res = trimCount - 1 } else if(response.liked==false){ $('.like-btn{{ request.path }}').css("color","black"); res = trimCount + 1 } } }) }) -
translating simple curl call to python/django request
I'm attempting to translate the following curl request to something that will run in django. curl -X POST https://api.lemlist.com/api/hooks --data '{"targetUrl":"https://example.com/lemlist-hook"}' --header "Content-Type: application/json" --user ":1234567980abcedf" I've run this in git bash and it returns the expected response. What I have in my django project is the following: apikey = '1234567980abcedf' hookurl = 'https://example.com/lemlist-hook' data = '{"targetUrl":hookurl}' headers = {'Content-Type': 'application/json'} response = requests.post(f'https://api.lemlist.com/api/hooks/', data=data, headers=headers, auth=('', apikey)) Running this python code returns this as a json response {} Any thoughts on where there might be a problem in my code? Thanks! -
Django static tags don't recognize cPanel
enter image description here this is my HTML file -
Can a user barge into django server as another user and perform operatn if he changes info in the frontend if we are using session authentication?
Hey guys I am confused and was thinking about this problem for sometime now, I am storing the current user's username in the session storage, and I have another page in which I use the stored username for an api call, it can be any requests. Eg. a post can be deleted by its author only, suppose, the url is api/<slug>/delete and in the frontend I have enabled the delete button only for the corresponding user, what if he edits the front end page and changes it to his username or what if I use the stored username to check that condition? And if he sends a delete request successfully from the frontend, does the django server able to determine that the user in the current session is not the real owner and has tweaked it in the frontend? Ps. This might be a foolish question, but I am a beginner and quite confused. Thanks. -
FOREIGN KEY constraint failed while trying to delete an object related
so i have these models in my app: from django.db import models from accounts.models import Vendedor class Comissao(models.Model): porcentagem = models.FloatField() def __str__(self): return str(self.porcentagem) class Venda(models.Model): vendedor = models.ForeignKey(Vendedor, on_delete=models.DO_NOTHING) comissao_venda = models.ForeignKey(Comissao, on_delete=models.DO_NOTHING) data_venda = models.DateField(auto_now_add=True) valor_venda = models.FloatField() descricao_venda = models.CharField(max_length=60) @property def valor_a_receber(self): return self.comissao_venda.porcentagem * self.valor_venda def __str__(self): return str(self.vendedor) and my problem is when i try to delete Comissao object i get this error: FOREIGN KEY constraint failed i´ve been hours stuck in this error, hope can someone help me...XD -
Cannot detect RTE or MLE of python code using python subprocess module
I am trying to build a simple judge that can execute C/C++ or Python codes...I am using python subprocess module for the command execution in my django project...I am also constraining time limit and memory limit using "ulimit" in the command...Though I can detect RTE MLE or CE for C/C++ code using the process's returncode, but python code doesn't fall on the same pattern..I was able to detect TLE as it returns 147 returncode...but for RTE MLE or CE it has returncode 1 whereas for C/C++ code each had different returncode... Is there a way to solve this issue? -
How to write Model Manager To get Average score?
I am learning django model and its manager. I am given to add find averge score from model manager. Here is my models. class Hotel(models.Model): name = models.CharField(max_length=100, unique=True) user = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Review(models.Model): content = models.TextField() score = models.DecimalField( max_digits=3, validators=[validate_score], decimal_places=1 ) reviewed_by = models.ForeignKey(User, on_delete=models.CASCADE) hotel = models.ForeignKey(Hotel, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) show_review = models.BooleanField(default=False) I want to get average score from models manager when I i query the hotels. Sorry for noob question it will be great help. -
how do I properly handle rest responses?
I want to handle error responses on Django restful framework to fit my needs, but I would like to know where exactly, and how I can handle properly those error responses like 400,200,403 in my case I want to return error 400 if query params are missing or None class ServiceViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): queryset = Service.objects.all() serializer_class = ServiceSerializer def get_queryset(self): domain = self.request.query_params.get('domain', None) domain_id = Domain.objects.filter(name=domain).first() if domain is not None: self.queryset = self.queryset.filter(domain=domain_id) return self.queryset -
Django, How to assign an ID to an anonymous user?
How to assign an ID to an anonymous user in Django in order to track his activity on this ID and restrict voting for example for a day. -
How can I use range in a for loop and use the range object as an index in a Django template?
I am trying to loop through a list of items to display in a Django template. I have read up on how you can create a range object in a few different ways to pass into the context. What I haven't been able to find, is how you can use the range object as an index. Is there a way to do this? Let's say I am passing a list in like so: return render(request, 'index.html', {'lst': lst, 'range': range(0, len(lst), 3)}) What I want: {% for i in range %} {{lst.i.color}} {{lst.i+1.price}} In my reading, I've seen how you can create a range object and use it like {{lst.i.color}}, but are you able to also do something like {{lst.i+1.color}}? If so, an example would be great. I know that lst.i+1.color does not work. Thanks for your time. -
Return request then do calculations django
I have a form, and I need to do some calculations (writing to a database, extract data etc. etc.) which takes some time. I want to do these calculation in the background i.e after the return. Right now the user are waiting for long_taking_calculation_function to finish before return redirect("my_template") which is not very userfriendly - is there a way to do it the other way round? def add_data(request): user = request.user instance = MyModel(user=user) form = MyModel_form(request.POST,instance = instance) if request.method == "POST": if form.is_valid(): #Do some calculations long_taking_calculation_function() return redirect("my_template") return render(request, "my_app/my_template.html") -
I got error when I click in Like button in Django
I got error when I click in like button in Django Video matching query does not exist. the traceback video_obj = Video.objects.get(id=video_id) I follow tutorial in youtube I got error when I click in like button the error appear how I can solve this problem my view def like_unlike_videos(request): user = request.user if request.method == 'POST': video_id = request.POST.get('video_id') video_obj = Video.objects.get(id=video_id) account = Account.objects.get(username=user) if account in video_obj.liked.all(): video_obj.liked.remove(account) else: video_obj.liked.add(account) like, created = Like.objects.get_or_create(username=account, video_id=video_id) if not created: if like.value == 'Like': like.value = 'Unlike' else: like.value = 'Like' else: like.value = 'Like' video_obj.save() like.save() data = { } data = { 'value': like.value, 'likes': video_obj.liked.all() } return render(request ,'video/the_video.html', data) my template <form action="{% url 'video:like-video-view' %}" method="POST" class="like-form" id='{{video.id}}'> {% csrf_token %} <input type="hidden" name="post_id" value={{video.id}}> <button type="submit" class="ui button like-btn{{video.id}}"> {% if account not in video.liked.all %} Like {% else %} Unlike {% endif %} </button> <div class="ui grid"> <div class="column"> <div class="like-count{{video.id}}"> {{video.num_likes}} </div> </div> <div class="column"> likes </div> </div> </form> -
How to create a parent model object while updating the child model object at a same time in nested serialization in Django Rest?
I have an order model which has a field billing_details which is a foreign key to BillingDetails model. I have already created order object. Now I have to create BillingDetails object and update the order object with data saving to billing_details field. My models: class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) #items = models.ManyToManyField(OrderItem,blank=True, null=True,related_name="order_items") start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) billing_details = models.OneToOneField('BillingDetails',on_delete=models.CASCADE,null=True,blank=True,related_name="order") def __str__(self): return self.user.email class BillingDetails(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) first_name = models.CharField(max_length=50,blank=True,null=True) last_name = models.CharField(max_length=50, blank=True, null=True) email = models.EmailField(blank=True, null=True) phone = models.CharField(max_length=50,blank=True,null=True) country = models.CharField(max_length=50,blank=True,null=True) city = models.CharField(max_length=50,blank=True,null=True) address = models.CharField(max_length=100,blank=True,null=True) postal = models.CharField(max_length=50,blank=True,null=True) def __str__(self): return self.address My serializers: class OrderBillingSerializer(serializers.ModelSerializer): class Meta: model = Order fields = ['id', 'user', 'start_date', 'ordered_date', 'ordered', 'order_items', 'billing_details'] class BillingCreateSerializer(serializers.ModelSerializer): order = OrderBillingSerializer() user = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = BillingDetails fields= ['id', 'user', 'order', 'first_name','last_name','email','phone','country','city','address','postal'] def update(self, instance, validated_data): user = self.context['request'].user order_data = validated_data.pop('order') Here I tried to write update method but dont know how to move forward from this. I have to create a BillingDetails object and update the Order model object with that BillingDetails object in billing_details field. My view: class AddBillingDetailsView(ListCreateAPIView,mixins.UpdateModelMixin): permission_classes = [IsAuthenticated] queryset = … -
Database error with MariaDB/Django. Why is it asking if I installed mysqlclient?
EDIT: This is Ubuntu 18.04 I recently did a database wipe on my django 2.2.7 python 3 project. The why is because I switched PC's and wanted a fresh MariaDB install. But I think this pc had some stuff already on it so here's what I did: I followed the instructions on this page https://mariadb.com/kb/en/uninstall-or-delete-mariadb-completely-for-re-installation/ First uninstalling and then checking the packages installed as instructed and I deleted those too. Then I followed this instruction to install https://www.digitalocean.com/community/tutorials/how-to-install-mariadb-on-ubuntu-18-04 However now that I am trying to fill the database using my django code (that used to work just fine). I'm getting the following error when running python3 manage.py makemigrations: Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/django/db/backends/mysql/base.py", line 15, in <module> import MySQLdb as Database File "/usr/local/lib/python3.6/dist-packages/MySQLdb/__init__.py", line 18, in <module> from . import _mysql ImportError: libmariadbclient.so.18: cannot open shared object file: No such file or directory The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 357, in execute django.setup() File "/usr/local/lib/python3.6/dist-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.6/dist-packages/django/apps/registry.py", line 114, … -
Celery. Create too many tasks
I run the same code on my local computer and remote. I don't understand why, in the local case, one worker and one task are launched. In the case of the remote computer, celery creates five tasks. app.conf.beat_schedule = { "create_new_avatar": { "task": "telegram_user.tasks.telegram_change_avatar", "schedule": crontab(), } } I would like celery to do one task in one minute. I am run : celery worker -A config.celery_app -B -l info -n other --concurrency=1 Result on local computer: [tasks] . telegram_user.tasks.telegram_change_avatar [2021-02-28 17:50:04,651: INFO/MainProcess] Connected to amqp://guest:**@127.0.0.1:5672// [2021-02-28 17:50:04,672: INFO/MainProcess] mingle: searching for neighbors [2021-02-28 17:50:05,591: INFO/Beat] beat: Starting... [2021-02-28 17:50:05,676: INFO/Beat] Scheduler: Sending due task create_new_avatar (telegram_user.tasks.telegram_change_avatar) [2021-02-28 17:50:06,064: INFO/MainProcess] mingle: all alone [2021-02-28 17:50:06,102: INFO/MainProcess] celery@other ready. [2021-02-28 17:50:06,119: INFO/MainProcess] Received task: telegram_user.tasks.telegram_change_avatar[827646b1-6587-4de9-b7b8-1fdc3f6a8d08] [2021-02-28 17:50:07,022: INFO/ForkPoolWorker-2] Connecting to 149.154.167.51:443/TcpFull... [2021-02-28 17:50:07,299: INFO/ForkPoolWorker-2] Connection to 149.154.167.51:443/TcpFull complete! [2021-02-28 17:50:08,323: INFO/ForkPoolWorker-2] Uploading file of 108247 bytes in 1 chunks of 131072 [2021-02-28 17:50:09,379: INFO/ForkPoolWorker-2] Uploading file of 108247 bytes in 1 chunks of 131072 [2021-02-28 17:50:10,602: INFO/ForkPoolWorker-2] Disconnecting from 149.154.167.51:443/TcpFull... [2021-02-28 17:50:10,603: INFO/ForkPoolWorker-2] Disconnection from 149.154.167.51:443/TcpFull complete! [2021-02-28 17:50:10,616: INFO/ForkPoolWorker-2] Avatar is changed in 2021-02-28 17:50:10.615904 But the same thing looks different on the remote server. [tasks] . telegram_user.tasks.telegram_change_avatar [2021-02-28 18:01:37,130: … -
Django transforming function based view into class based view
Im trying to convert a fucntion based views into a class based views but have hit a wall with this function. @login_required(login_url=settings.LOGIN_URL) def list_bugs_view(request, id): queryset = Bug.objects.filter(project=id) project = Project.objects.filter(id=id) context = { 'bug_list': queryset, 'project': project } return render(request, 'bugs/bug_list.html', context) {% extends 'base.html' %} <-- bug_list.html --> {% block content %} <h1>{{ project.name }}</h1> <table class="table table-striped"> <thead class="thead-dark"> <tr> <th scope="col">Bug ID</th> <th scope="col">Name</th> <th scope="col">Status</th> <th scope="col">Severity</th> <th scope="col">Creator</th> <th scope="col">Created</th> <th scope="col">Actions</th> </tr> </thead> <tbody> {% for bug in bug_list %} <tr> <th scope="row">{{ bug.id }}</th> <td>{{ bug.name }}</td> <td>{{ bug.status }}</td> <td>{{ bug.severity }}</td> <td>{{ bug.bug_creator }}</td> <td>{{ bug.bug_created }}</td> <td></td> </tr> {% endfor %} </tbody> </table> {% endblock %} I have already used the generic.ListView to convert another function based view but do not know how to filter the bugs by project which is reciving an id from: # Class based view responsible for creating a project. class ProjectCreateView(LoginRequiredMixin, CreateView): model = Project template_name = 'projects/project_create.html' form_class = ProjectForm success_url = '/projects/create' # This come from LoginRequiredMixin # Redirects page to LOGIN_URL page (the value of which is set in settings.py) when the user tires accessing the projects/project_create page but is not … -
Django poll with many options how to limit visibility?
I am building voting apps in django. I have little experience in programming and in django in particular. And here is the problem I ran into. My application should be able to receive an answer to three types of question: one answer multiple answer options your answer (free text) Depending on the conditions of the survey, the user should see one of the answer options. But when I post a survey, the user sees all three answer options. How can I fix this? I hope for your help models.py class Poll(models.Model): title = models.CharField(max_length=256) start_date = models.DateField(auto_now_add=True) end_date = models.DateField() description = models.TextField(max_length=1024, blank=True) def __str__(self): return self.title TYPES_OF_POLLS = ( ('free_text', 'free text input'), ('option', 'only one choice'), ('options', 'many choices'), ) class Question(models.Model): poll = models.ForeignKey(Poll, on_delete=models.CASCADE) text = models.CharField(max_length=250) poll_type = models.CharField(max_length=50, choices=TYPES_OF_POLLS, verbose_name='Types of polls') def __str__(self): return str(self.text) class Option(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) text = models.CharField(max_length=256) def __str__(self): return f'{self.question} - {self.text}' class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) one_option = models.ForeignKey(Option, on_delete=models.CASCADE, null=True, related_name='option', blank=True) many_options = models.ManyToManyField(Option, null=True, blank=True) text_input = models.TextField(null=True, blank=True) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return f'{self.question} - {self.one_option} - {self.many_options} - {self.text_input} ' forms.py class AnswerForm(ModelForm): … -
Django: Renewed access token can be set as HttpOnly cookie in middleware but response from re-authenticated view is not coming
In a custom middleware, I am renewing the access token from refresh token in the process_view() function. The tokens are set as HttpOnly cookies. In the process_view() function, I am calling the SimpleJWT TokenRefreshView() with http://127.0.0.1:8000/api/auth/refresh/ and setting its response access token string as HttpOnly cookie but, the strange thing is, It's only setting the token as cookie but, the response of the re-authenticated view in which the token was expired is not coming. Here, the access token is valid as this page was requested just after login: Here you can see that after getting the new access token, the response body has not come, but in the cookie, the new access token is set: My middleware: class AuthorizationHeaderMiddleware: def __init__(self, get_response=None): self.get_response = get_response def process_view(self, request, view_func, view_args, view_kwargs): view_name = '.'.join((view_func.__module__, view_func.__name__)) if request.path == '/api/auth/login/': # do nothing return None elif request.path == '/api/auth/refresh/': # do nothing return None else: # for every other view try: access_token = request.COOKIES['access'] key = settings.SECRET_KEY decoded_access_token = jwt.decode(access_token, key, algorithms=["HS256"]) except jwt.ExpiredSignatureError: # if token has expired refresh_cookie = request.COOKIES['refresh'] data = {"refresh": refresh_cookie} url = 'http://127.0.0.1:8000/api/auth/refresh/' resp = requests.post(url, data=data) access_token_string = json.loads(resp.text)["access"] response = HttpResponse() response.set_cookie('access', access_token_string, … -
Best way to use the canvas tag in django templates
I have a django template that currently uses an img tag to load an image based on a url from the database. I find I now need to draw a box at a certain position on the image when a user hovers over a button. The position of the box is determined by which button the user hovers over, and the box positions are loaded on the template from the database depending on which image is loaded. Is the best solution to replace the img tag with a canvas tag? If so, what is the django way of getting the url from the database to the javascript code so the image is loaded? Would I use the new Html5 custom attribute 'data-' in the canvas tag to provide the url to the script to load the image? It seems to be rather round-about to load the page, then get the url, then load the image, then display the image on the page. Is there a better way? Thanks! Mark -
How do I create an app for anonymous voting in Django?
I am doing an anonymous voting system on django, and this problem has led me to a dead end. Unregistered users can participate in the vote, whose votes I can track by the assigned ID. I have little experience with django, so please do not judge strictly. I will be glad for your help. When I try to cast anonymously, I get the Cannot assign error : "<SimpleLazyObject: <django.contrib.auth.models.AnonymousUser object at 0x7f5e345d0d30 >>": "Answer.user" must be a "User" instance. models.py class Poll(models.Model): title = models.CharField(max_length=256) start_date = models.DateField(auto_now_add=True) end_date = models.DateField() description = models.TextField(max_length=1024, blank=True) def __str__(self): return self.title TYPES_OF_POLLS = ( ('free_text', 'free text input'), ('option', 'only one choice'), ('options', 'many choices'), ) class Question(models.Model): poll = models.ForeignKey(Poll, on_delete=models.CASCADE) text = models.CharField(max_length=250) poll_type = models.CharField(max_length=50, choices=TYPES_OF_POLLS, verbose_name='Types of polls') def __str__(self): return str(self.text) class Option(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) text = models.CharField(max_length=256) def __str__(self): return f'{self.question} - {self.text}' class Answer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) one_option = models.ForeignKey(Option, on_delete=models.CASCADE, null=True, related_name='option', blank=True) many_options = models.ManyToManyField(Option, null=True, blank=True) text_input = models.TextField(null=True, blank=True) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return f'{self.question} - {self.one_option} - {self.many_options} - {self.text_input} ' views.py def home(request): polls = Poll.objects.all context = {'polls':polls} return render (request, … -
Django authentication for the API
So I tried to write a simple part of the website that does the following: Pick a date Scrapes a website to get data based on that date Puts out a list of the data and allows you to add these as songs to spotify playlist I made it work, but I would like to learn how one does this properly. I am very new to this framework. I will break down some issues: First, files (don't worry about SPOTIPY, I used to use spotipy package and made this work very nicely in the console, but I didn't like it for the web that much. Project files: urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), path('billboard100/', include("billboardapp.urls")), path('accounts/', include('allauth.urls')), ] settings.py """ Django settings for webpage project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from dotenv import load_dotenv load_dotenv() import os from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in … -
Get field/column from related table and filter it
I have models: class Animal(models.Model): pass class RegionAnimal(models.Model): price = models.DecimalField(...) animal = models.ForeignKey(Animal, ..., related_name="region_animals") class LocationAnimal(models.Model): count = models.PositiveIntegerField(default=0) animal = models.ForeignKey(Animal, ..., related_name="location_animals") I have a RegionAnimalViewSet(mixins.ListModelMixin, GenericViewSet) where I can filter QuerySet with animal and region fields using django_filters. I want to add to response count field from LocationAnimal using location field. How can I achieve this?