Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Users can Create Models - Django - Python
I'm working on a Django website and for my next step, I am taking the Models that I have created in the code and allowing Users to create them. I have found no information on this and Im wondering if anyone else has. I need the ability for users to create their own fields and be able to add data to those fields. Essentially creating their own models. Thanks! -
Cropper JS lowers quality of image after cropping *Django Application*
I am having issues with the image quality of the cropped photos. Everything works and displays correctly, but the only issue is that the image quality diminishes after the image is cropped. The images look the same in the database as they do in the frontend (Low Quality). I know the question was answered Using Cropper js Image quality get reduced after cropping, but I still can't get it work. If anyone could help that would be much appreciated. base.html <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link href= "{% static 'css/main.css' %}" rel="stylesheet"> <link href= "{% static 'css/profile.css' %}" rel="stylesheet"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> ... <div class="container"> {% block content %} {% endblock %} </div> <script src="{% static 'js/jquery-3.1.1.min.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> <script src="{% static 'js/cropper.min.js' %}"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.css" integrity="sha512-+VDbDxc9zesADd49pfvz7CgsOl2xREI/7gnzcdyA9XjuTxLXrdpuz21VVIqc5HPfZji2CypSbxx1lgD7BgBK5g==" crossorigin="anonymous" referrerpolicy="no-referrer" /> profile_uploads.html <script> $(function () { /* SCRIPT TO OPEN THE MODAL WITH THE PREVIEW */ $("#id_file").change(function () { if (this.files && this.files[0]) { var reader = new FileReader(); reader.onload = function (e) { $("#image").attr("src", e.target.result); $("#modalCrop").modal("show"); } reader.readAsDataURL(this.files[0]); } }); /* SCRIPTS TO HANDLE THE CROPPER BOX */ var $image = $("#image"); var cropBoxData; var canvasData; $("#modalCrop").on("shown.bs.modal", function () { $image.cropper({ viewMode: … -
ImageFile doesn`t work, don`t know what the problem is in
I'm trying to upload a picture, but it doesn't work. No mistake returns, like if it is uploaded and self.validated_data['picture'] or serializer.self.validated_data['picture'] prints are not empty, but 'picture' in JSON stays null - it mustn`t. Nothing loads to media files, nothing is in DB Views @api_view(['GET', 'POST']) def api_pictures(request): if request.method == 'GET': pictures = Picture.objects.all() serializer = PictureSerializer(pictures, many=True) return JsonResponse(serializer.data, safe=False) if request.method == 'POST': serializer = PictureSerializer(data=request.data) if serializer.is_valid(): serializer.save() print(serializer.validated_data['picture']) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) #Models class Picture(models.Model): pic_name = models.CharField(max_length=255, blank=True) picture =models.ImageField(upload_to='media_site/',blank=True, height_field='height', width_field='width') url = models.URLField(blank=True, null=True, max_length=500) height = models.IntegerField(blank=True, null=True) width = models.IntegerField(blank=True, null=True) #Urls urlpatterns = [ path("admin/", admin.site.urls), path("api/", include(router.urls)), path("api/images/", api_pictures), path("api/images/<int:pk>", detail_pictures), ] #Serializers.py class PictureSerializer(serializers.ModelSerializer): @staticmethod def name_parser(object_name): parser = re.search(r'[^/]*$', str(object_name)) return parser[0] def save(self): if 'picture' not in self.validated_data.keys(): url = self.validated_data['url'] result = urllib.request.urlopen(url=url) img = BytesIO(result.read()) converted_img = InMemoryUploadedFile(img, None, self.name_parser(url), 'image/jpeg', sys.getsizeof(img), None) print(converted_img) self.validated_data.update({'picture': converted_img}) else: self.validated_data.update({'picture': self.validated_data['picture']}) if 'pic_name' not in self.validated_data.keys(): name = self.name_parser(self.validated_data['picture']) self.validated_data.update({'pic_name': name}) class Meta: model = Picture fields = ('id', 'pic_name', 'picture', 'url', 'width', 'height', 'parent_picture') result But 'picture' mustn`t be null :(((( When i upload it self.validated_data['picture'] is not empty. Django returns … -
Why I'm unable to download my document with django? and how to do it?
I'm new to django and still learning, and I got here, in my own infinite loop, if I do how I sholud it be but i have an errors and it won't work, but if I do it like this there are no errors but it won't work. I want to user to be able to create excel template as he wish, this is simplified version that I want to work, just input few information and on base of that to be able to create excel template. This is views.py from django.http import HttpResponse from django.shortcuts import render import xlsxwriter from xlsxwriter import workbook from django.forms import Form, CharField, ChoiceField, IntegerField from django.core.validators import MaxValueValidator, MinValueValidator def home(request): return render(request, 'my_app/home.html') def create_template(request): return render(request, 'my_app/create_template.html') class TemplateForm(Form): doc_name = CharField(label='Document name') sheetnames = CharField(label='Sheetnames') choices = [] for year in range (1900, 2050): choices.append( (year, year) ) year1 = ChoiceField(label='Starting Year', initial=2021, choices=choices) year2 = ChoiceField(label='Ending Year', initial=2022, choices=choices) row_names = CharField(label='Column names') def create_template(request): if request.method == 'GET': form = TemplateForm() return render(request, 'my_app/create_template.html', {'form':form}) else: form = TemplateForm(request.POST) def create_form(doc_name, sheetnames, years, row_names): workbook = xlsxwriter.Workbook(doc_name + '_template.xlsx') worksheet_introduction = workbook.add_worksheet( "introduction" ) for i in sheetnames: … -
How to display a custom number of model records
In the database, I have 20 model objects, when I enter model page, I show all 10 records. I want to make a field defining how many records display, for example 10 entries. Then the remaining 10 entries will be on 2 page. -
Inner joins with timestamps in Django ORM
Django documentation states to check the ORM before writing raw SQL, but I am not aware of a resource that explains how to perform inner joins between tables without foreign keys. Many of the tables in my database need to be joined by time-related properties or intervals, which to my knowledge do not serve well as foreign keys. For example, in this basic example I need to first take a subset of change_events, and then join a different table ais_data on two separate columns: models.py class AisData(models.Model): navstatus = models.BigIntegerField(blank=True, null=True) start_ts = models.DateTimeField() end_ts = models.DateTimeField(blank=True, null=True) destination = models.TextField(blank=True, null=True) draught = models.FloatField(blank=True, null=True) geom = models.PointField(srid=4326) imo = models.BigIntegerField(primary_key=True) class Meta: managed = False db_table = 'ais_data' unique_together = (('imo', 'start_ts'),) class ChangeEvent(models.Model): event_id = models.BigIntegerField(blank=True, null=True) imo = models.BigIntegerField(blank=True, null=True) timestamp = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'change_event' First I take a subset of change_events which returns a QuerySet object. Using the result of this query, I need to get all of the records in ais_data that match on imo and timestamp - so the raw SQL would look like this: SELECT ce.*, ad.geom FROM change_events ce JOIN ais_data ad WHERE ce.imo … -
Django Foreign Key chain object write?
i am working on management command that will write some data from json to database tables result is i would like to write objects that belong to table which is ForeignKey to another table and that table is also ForeignKey to its root table , so objects in table C(HostOsScanned) >> ForeignKey table B(HostScanned) wich is >> ForeignKey to table A(SiteAssest) Table from models is shown below i know how to write in case of A>B table but not with such scenario with chain of dependency's of foreign key like follow example below Please help Thanks ---example-- def handle(self, *args, **options): scan_name_id=SiteAssest.objects.get(scan_name=options['scan_name_id']) scan_iphost = HostScanned( host_ip_name=options['host_ip_name'], resolved_hostname=options['resolved_hostname'], resolve_type =options['resolve_type'], mac_address=options['mac_address'], mac_addr_type=options['mac_addr_type'], mac_vendor=options['mac_vendor'], host_state=options['host_state'], host_state_method=options['host_state_method'], host_state_ttl=options['host_state_ttl'], scan_name_id=int(scan_name_id.id), ) try: scan_iphost.save() self.stdout.write(self.style.SUCCESS('Success HostScanned write')) except Exception as e: print('id scanned',scan_name_id.id) self.stdout.write(self.style.ERROR(e)) --model--- class SiteAssest(models.Model): scan_name = models.CharField(max_length=250,blank=False) site_name = models.CharField(max_length=250,blank=False) location_name = models.CharField(max_length=250,blank=False) # Geo location lon = models.FloatField() lat = models.FloatField() site_ip_range1 = models.CharField(max_length=250,blank=True) site_ip_range2 = models.CharField(max_length=250,blank=True) site_ip_range3 = models.CharField(max_length=250,blank=True) #new entry scan_time_start = models.DateTimeField(default=datetime.date.today()) scan_timestr_start = models.CharField(max_length=250,blank=True) scan_time_end = models.DateTimeField(default=datetime.date.today()) scan_timestr_end = models.CharField(max_length=250,blank=True) scan_elapsed = models.IntegerField(blank=True, null=True) scan_exit_resault = models.CharField(max_length=50,blank=True) scan_args = models.CharField(max_length=250,blank=True) nmap_version = models.CharField(max_length=50,blank=True) # end new entry last_scaned = models.DateField(auto_now_add=False, null=True) TASK_STATUS_CHOICES = [ ('ID', 'IDLE'), ('RU', … -
ConnectionResetError while using fetch API to pass data to Django view which posts data to external api
I am trying to implement Opayo(Sagepay) with Django. From my template I am trying to send a card_identifier variable from my template to a view using fetch API. The view will then use the requests package to post this card_identifier along with other data to the an api to process the payment. The api should respond with a JsonResponse which I want to pass back to the template or use to perform a redirect to a payment success or failure page. async function processPayment() { var card_identifier = document.querySelector('[name="card-identifier"]').value var url = "{% url 'sagepay:processing_payment' %}" await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json', 'X-CSRFToken': csrftoken, }, body: JSON.stringify({ merchantSessionKey: merchantSessionKeyContext, card_identifier: card_identifier, }) }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.log(error)) } In the view I am collecting this card_identifier variable and using it to make the payment via a post request to the sagepay api. def process_payment(request): body = json.loads(request.body) card_identifier = body["card_identifier"] merchantSessionKey = body["merchantSessionKey"] basket = Basket(request) total = str(basket.get_total_price()) total = total.replace(".", "") amount = int(total) headers = { "Authorization": "my key goes here", } data = { "transactionType": "Payment", "paymentMethod": {"card": {"merchantSessionKey": merchantSessionKey, "cardIdentifier": card_identifier}}, "vendorTxCode": "ggmachiSnesdaqjcjjjhqsbxjka", "amount": amount, "currency": "EUR", … -
Django Tool with Mariadb inside a Docker Container
I am kind of confused on what will be the right way to host my django application and make it independent to run on any machine. So basically, what my current plan is: I have a repository in GitLab of my Django Application. I will clone it via script at some location via ssh. Inside that repository I will perform python3 manage.py makemigrations python3 manage.py migrate docker build . -t $1 docker run -d -p 8000:8000 $1 Where $1 will be the parameter I will pass to name my docker image. My Dockerfile looks like : FROM python:3.6 RUN mkdir /Folder_Name WORKDIR /Folder_Name ADD . /Folder_Name RUN pip3 install -r requirements.txt EXPOSE 8000 CMD python3 manage.py runserver 0.0.0.0:8000 --noreload So this thing is working fine. But I feel that their is more legit way to perform this in one go. So this is about containerizing my Django Application. Before all this we also need a database. Right? Now the thing is, My database is MariaDB, which is again running on docker. For that I need to login to my docker container of MariaDB , and perform actions to Create Database (CREATE DATABASE DB_NAME CHARACTER SET UTF8;) Create User CREATE USER … -
delete and get the sessionid in react and javascript
I make an app in Django and react And I want to check with the server if the user is still authenticated if the user is not authenticated anymore I send 401 becks to the client so I have some questions how I can check if there is sessionid in cookies? I tried document.cookie but it did not work how to delete the sessionid?? Can someone help me please? and sorry for my English -
implementing a create function for a Serializer class containing foreignkey (Django Rest Framework)
So, this is how i have implemented the class: class VenueSerializer(serializers.ModelSerializer): city = serializers.StringRelatedField(many=True) class Meta: model = Venue fields = '__all__' def create(self, validated_data): venue = Team( name=validated_data['name'] #I know this is wrong but i just wanted to demonstrate what is it that i need to get done #city is the foreign key referencing to the model City city=validated_data['city'] ) venue.save() return venue So i have a model for venues, and each venue has to be associated with the model city. I am new to the REST Framework and i can't figure out a way to create an instance of the venue model while setting the value of the city field. Can someone please help me with this? Than you -
Django: Saving created object to user?
I have a model of uploads and i want to associate the uploaded images to the user so that later each user can only view his objects so so i m trying to save the created objects to the authenticated user, but it's not working and i keep getting owner =null on my model class Uploads(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title=models.CharField(max_length=500,default='none') image=models.ImageField(upload_to='media',unique=True) created_at = models.DateTimeField(auto_now_add=True) associatedFile=models.ForeignKey(to=File, on_delete=models.CASCADE,null=True) owner=models.ForeignKey(User,related_name="uploads", on_delete=CASCADE,null=True) class IsOwnerFilterBackend(filters.BaseFilterBackend): def filter_queryset(self, request, queryset, view): queryset=Uploads.objects.all() return queryset.filter(owner=request.user) class UploadView(viewsets.ModelViewSet): queryset=Uploads.objects.all() serializer_class=UploadSerializer filter_backends = (IsOwnerFilterBackend,) @api_view(['GET', 'POST']) def methodes(self,request,*args,**kwargs): if request.method=='POST': serializer=UploadSerializer(data=request.data) if serializer.is_valid(): serializer.save(owner=self.request.user) return Response("test_token success", status=status.HTTP_200_OK) return HttpResponse({'message':'error'},status=400) elif request.method=='GET': images=Uploads.objects.filter(owner=self.request.user) serializers=UploadSerializer(images[0],many=False) return JsonResponse(serializers.data,safe=False) class UploadSerializer(serializers.ModelSerializer): image = Base64ImageField( max_length=None, use_url=True, ) owner=serializers.ReadOnlyField() class Meta: model = Uploads fields = '__all__' -
How to display for user that his wishlist is empty?
Question like in title. When i tried this views.py, error doesn't occur but site doesn't want to show, i can see only code. Any solutions? def wishlist(request): if request.user.is_authenticated: user = request.user.id if List.objects.filter(user=user).exists(): context = List.objects.filter(user=user) error = 'Your wishlist is empty' else: context = List.objects.filter(user=user) else: context = WishList(request) return render(request, 'wishlist/wishlist.html', {'wishlist': context}, {'error': error}) -
Heroku release phase commands are not executed
I try to deploy a django application on heroku using a build manifest. The application seems to be deployed correctly, but the commands in the release phase do not seem to be executed. This is my heroku.yml: build: docker: web: Dockerfile release: image: web command: - python manage.py migrate - python manage.py collectstatic --noinput run: web: gunicorn hello_django.wsgi:application --bind 0.0.0.0:$PORT This is my Dockerfile: FROM python:3.9-slim ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONBUFFERED 1 RUN apt-get update \ && apt-get install -y --no-install-recommends \ postgresql-client \ && rm -rf /var/lib/apt/lists/* WORKDIR /usr/src/app # install dependencies RUN pip install --upgrade pip COPY requirements.txt ./ RUN pip install -r requirements.txt # copy source code to container COPY ./src . # create directory for statics RUN mkdir staticfiles The commands specified in the release phase are not executed. I know that, because the database is not being migrated and the staticfiles directory is empty. I also know that the rest of my application is actually configured correctly, because when I include this line in my Dockerfile at the end: RUN python manage.py collectstatic then the statics are collected and the application is running. I also installed the plugin heroku-manifest with this command: heroku plugins:install @heroku-cli/plugin-manifest … -
How to filter on date in Django Rest Framework
I wrote the following code, trying to filter on dates using DRF: class FixtureFilter(django_filters.FilterSet): date = django_filters.DateFilter('date__date', lookup_expr='exact') class Meta: model = Fixture fields = ['date'] class FixtureViewSet(viewsets.ReadOnlyModelViewSet): queryset = Fixture.objects.all().order_by('-date') serializer_class = FixtureSerializer permission_classes = [permissions.IsAuthenticated] filter_class = FixtureFilter When I make a call to the API like http://localhost:8000/api/v1/fixtures?date=2021-11-29 it returns me more than 1 object whereas it should just return 1 object. How do I implement this properly? -
Edit Django objects with bootstrap modal form
This is something I've not done before as I'm still a beginner. Am using bootstrap form (class="modal fade") to add new objects into my model with Ajax. Now my problem is how I can edit objects with this same form. Also, I'm using django_tables to render the objects in my html. Below is my tables.py file class ObjectTable(tables.Table): class Meta: attrs = {'class': 'table table-bordered table-striped mb-0'} name = tables.Column(accessor=A('name'), verbose_name='Name') address= tables.Column(accessor=A('url'), verbose_name="Address") edu_level= tables.TemplateColumn('{{record.level}}') created_at = tables.Column(accessor=A('created_at'), verbose_name="Date Created") options = tables.TemplateColumn( '<button class="btn btn-info btn-sm" data-toggle="modal" data-target="#link-edit"><i class="feather ' 'icon-edit"></i> &nbsp;Edit </button> ' '<button class="btn btn-danger btn-sm" data-toggle="modal" data-target="#link-delete"><i class="feather ' 'icon-trash-2"></i> &nbsp;Delete </button>') Below is part of the form.html ... <div class="modal fade" id="link-edit" tabindex="-1" role="dialog" aria-labelledby="myExtraLargeModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Edit Link</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form class="edit-link-form"> <div class="row"> <div class="col-sm-6"> <div class="form-group"> <label class="floating-label" for="Name">Name</label> <input required type="text" name="name" class="form-control" id="EditName" placeholder="Enter the name of the link here"> </div> ... -
Is there any reason why Git erasing my Django templates content?
Before I commit, I run—'git status', and I see Git erased my Django templates content (if that makes any sense). This strange behavior happens occasionally. Can somebody explain what's going on? -
Django template slow to render: caching helps subsequent loads, but can I help the first?
I have a django app hosted on heroku, and I have a 'family album' page that loads a bunch of image thumbnails which link to a larger image detail page. (And the set of pictures can be different per user). Each of these thumbnails uses an image_link.html template. At the most there can be up to ~1100 of these thumbnails on the family album page, and it loads peachy in production. The problem: I wanted to add the option to have a little hover overlay, so that when you mouse over a thumbnail you can see an overlay of who the picture contains. (This is returned by a function on the Image class). I started with the image overlay code from w3schools here, and updated to show the list of people in each picture (instead of static text). This works great, but locally that page can take around 4-5 seconds to load, and when I deploy it to production (on heroku), it's taking forever: ~22 seconds on average, sometimes surpassing the 30 second timeout. (I'm using one Hobby Dyno). So I've done a couple things: cached the code in views.py that grabs all the images that'll display then I added … -
Make Django/DRF accept urls without trailing slash
Is it possible to avoid url redirections to url/ in Django/DjangoRestFramework? My point is that some frontend developers use url without trailing slashes and Django redirects such requests to url/ which slows down the API. Adding APPEND_SLASH = False to settings doesn't solve the problem as it returns 404 responses. -
Django many-to-many relationship with through table, how to prevent it doing a lot of queries?
I am working on an API for a D&D tool where I have campaigns, and people can be members of campaigns. I need to store extra information for each member of the campaign, so I am using a through model. class Campaign(models.Model): name = models.CharField(max_length=50) description = models.TextField() owner = models.ForeignKey(User, related_name='owned_campaigns', on_delete=models.CASCADE) members = models.ManyToManyField(User, related_name='campaigns', through='Membership') class Membership(models.Model): campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) is_dm = models.BooleanField(default=False) If I want to fetch all campaigns that the user is a member of, I can simply do something like this: >>> from auth.models import User >>> user = User.objects.get(pk=1) >>> campaigns = user.campaigns.select_related('owner') >>> print(campaign) This does an INNER JOIN to fetch the owner of the campaign, so that prevents having to do an extra query. Great! However, when I also want to return the array of members (with the nested user info for each member), then it does one extra query to fetch the members, and then one extra query for every member to fetch the user object. I am noticing this specifically in Django REST Framework where I have serializers like this: class MembershipSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = Membership fields = ["is_dm", "user"] … -
saving events in fullcalendar using django
I am trying to create a calendar but I can't save any event I want to save to my sqlite db I am using django and django reset framework i think the problem is with the serializer this is the request data it may help <QueryDict: {'title': ['test'], 'start': ['1630627200000'], 'end': ['1630713600000'], 'url': ['test']}> view.py class SnippetSerializer(serializers.Serializer): title = serializers.CharField(max_length=100) url = serializers.URLField(required=False, allow_blank=True) start = serializers.DateField(required=False) end = serializers.DateField(required=False) def create(self, validated_data): return CalendarEvent.objects.create(**validated_data) def update(self, instance, validated_data): instance.title = validated_data.get('title',instance.title) instance.url = validated_data.get('url',instance.url) instance.start = validated_data.get('start',instance.start) instance.end = validated_data.get('end',instance.end) instance.save() return instance class addDateEvents(APIView): authentication_classes = [] permission_classes = [] def post(self,request,**kwargs): serializer = SnippetSerializer(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) js $(document).ready(function() { $('#calendar').fullCalendar({ header: { left: 'prev,next today', center: 'title', right: 'month,agendaWeek,agendaDay', }, defaultDate: get_current_data(), navLinks: true, // can click day/week names to navigate views selectable: true, selectHelper: true, editable: true, eventLimit: true, // allow "more" link when too many events select: function(start, end) { var title = prompt('Event Title:'); var url = prompt('Event Url') var eventData; $.ajax({ url : 'http://127.0.0.1:8000/api/add/event', data :'title='+ title+'&start='+ start +'&end='+ end+'&url='+url, type : 'POST', success:function(json){ $('#calendar').fullCalendar('refetchEvents'); console.log('Event Added') } }) if (title) { eventData = { title: title, url … -
Get all information on 1 QueryDjango
I am trying to get all values in a single queryset, i have the following model: class Temporal(model.Models): id = models.UUIDField(default=uuid.uuid4, primary_key=True) value=models.CharField(max_length=60) created_at = models.DateTimeField(auto_now_add=True) date_start = models.DateTimeField(auto_now_add=True) date_end = models.DateTimeField(auto_now_add=True) rate_name = models.ForeignKeyField("RateName") concept_payment = models.CharField(max_length=60) order = models.IntegerField(null=True, blank=True) and some other fields... I am getting all the diferente concept_payment this way: energy_concepts = Temporal.objects.filter(rate_name=rate_name, date_start__month__lte=month_apply, date_end__month__gte=month_apply, concept_payment='Energy').first() demand_concepts = Temporal.objects.filter(rate_name=rate_name, date_start__month__lte=month_apply, date_end__month__gte=month_apply, concept_payment='Demand').first() other_concepts = Temporal.objects.filter(rate_name=rate_name, date_start__month__lte=month_apply, date_end__month__gte=month_apply, concept_payment='Others').first() taxes_concepts = Temporal.objects.filter(rate_name=rate_name, date_start__month__lte=month_apply, date_end__month__gte=month_apply, concept_payment='Taxes').first() and so on where the only difference is the concept_payment, So I was wonder if there is a way to get them all, using annotate instead of getting one by one, the concept payment are dynamic so I think I would have to get all the differents concetps first. Thanks in advance -
Invalid Credential Provided error on heroku
I try to link my django project to heroku and keep getting Invalid credentials provided. I have use heroku before but now I just don't understand what is happening I also get to see https://cli-auth.heroku.com/auth/cli/browser/8 which opens up in the web browser and shows bad request -
unsupported operand type(s) for -: 'method' and 'method'
I am building a Blog App and I was trying to implement up vote and downvote in blog. Than i thought about that If there are 4 upvotes and 2 downvotes then it will show only 2 votes Like :- upvotes - downvotes So I tried to implement it BUT when I try to do calculation in view than an error is keep showing unsupported operand type(s) for -: 'method' and 'method' models.py class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30,default='') vote_up = models.ManyToManyField(User,related_name='vote_up',blank=True) vote_down = models.ManyToManyField(User,related_name='vote_down',blank=True) views.py def blogpost_detail_view(request,pk): post = get_object_or_404(BlogPost,pk=pk) upvotes_count = post.vote_up.count downvotes_count = post.vote_down.count show = upvotes_count - downvotes_count context = {'show ':show ,'post':post} Traceback from Terminal Traceback (most recent call last): File "D:\app\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\app\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\app\views.py", line 31, in blogpost_detail_view show= upvotes_count - downvotes_count TypeError: unsupported operand type(s) for -: 'method' and 'method' I also tried by -= but it did show same error Than i tried by adding the calculation in brackets but same error. Any help would be much Appreciated. Thank You in Advance. -
JSONDecodeError when trying to make request counter with Django
So I wanted to make a "reqcount" thing in my django project using a JSON file but when I run it I get this error: Environment: Request Method: GET Request URL: http://localhost:8000/testing/reqcount/ Django Version: 3.2.6 Python Version: 3.8.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.messages', 'django.contrib.staticfiles', 'testing'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\chris\.virtualenvs\WEBSITE-PTmWcCQQ\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\chris\.virtualenvs\WEBSITE-PTmWcCQQ\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\chris\Desktop\WEBSITE\testing\views.py", line 17, in req_count return HttpResponse(json.load(f)) File "c:\users\chris\appdata\local\programs\python\python38\lib\json\__init__.py", line 293, in load return loads(fp.read(), File "c:\users\chris\appdata\local\programs\python\python38\lib\json\__init__.py", line 357, in loads return _default_decoder.decode(s) File "c:\users\chris\appdata\local\programs\python\python38\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "c:\users\chris\appdata\local\programs\python\python38\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None Exception Type: JSONDecodeError at /testing/reqcount/ Exception Value: Expecting value: line 1 column 1 (char 0) This is my views.py code (ignore the "hello" function): from django.shortcuts import render from django.http import HttpResponse import json def hello(request): return HttpResponse('Hello, World!') def req_count(request): # TODO: Update the amount of requests the "reqcount" url has gotten, then return it with open('..\\data.json', 'w+') as f: data = json.load(f) data['views']['reqcount']['reqs'] += 1 json.dump(data) return HttpResponse(data['views']['reqcount']['reqs']) NOTES: …