Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how can i substract time dates in django to gate the age of a post?
i want to display the age of video like "this video uploaded 2 days ago", "3 weeks and so on" i have tried this but not working #this is not working !! from django.db import models from datetime import datetime class Video(models.Model): video_upload = models.FileField(upload_to='media') video_detail = models.TextField(blank=True) video_title = models.CharField(max_length=100) pub_date = models.DateTimeField(auto_now=True) def age_of_video(self): return datetime.now() - self.pub_date def __str__(self): return self.title in template {% for video in all_videos %} {{ video.age_of_videos}} {% endfor %} -
Display images in Django using http links
I am a beginner in Django so please help me with this problem of mine. I am getting http links of images from a google api that i am calling. I want to show those images on my website but the photos are not showing up. My views.py file def hotel1(request): api_key = 'myAPIkey' url = "https://maps.googleapis.com/maps/api/place/textsearch/json?" if request.method == 'POST': city = request.POST['city'] query = str(city) r = requests.get(url + 'query=' + 'hotels in '+ query + '&key=' + api_key) x = r.json() y = x['results'] name = [] photo_reference = [] for i in range(len(y)): name.insert(i, y[i]['name']) photo_reference.insert(i, y[i]['photos'][0]['photo_reference']) a = list(zip(name,photo_reference)) url2 = "https://maps.googleapis.com/maps/api/place/photo?" photo_url = {} for i in range(len(y)): r = requests.get(url2 + 'maxwidth='+'400' + '&photoreference='+a[i][1]+ '&key=' + api_key) if r.status_code == 200: with open('D:/Travel app/travelX/mysite/static/mysite/images/hotels/' + query + a[i][0] + '.jpg', 'wb') as f: for chunk in r: f.write(chunk) photo_url[i] = r.url #get url of images return render(request, 'mysite/test.html', photo_url ) And my Html file is <form method="post" class="post-form" action="test.html"> {% csrf_token %} <div class="fields"> <div class="form-group"> <input type="text" class="form-control" placeholder="Destination City" name="city"> </div> <div class="form-group"> <input type="submit" value="Search" class="btn btn-primary py-3 px-5"> {% for value in photo_url.values %} <img src="{{value}}"/> {% endfor %} … -
Insert data in model from json in django
My Model: class Post_Data(models.Model): id = models.AutoField(primary_key=True) data = models.CharField(max_length=200) I need to insert the json data inside the model which will be passed in the form of "file" in postman. I tried: def post(self, request): json_file = request.FILES['json_file'] with open(json_file) as f: json_data = json.loads(f) a = Post_data(data=json_data) a.save() But it's not working. -
How can i use django templates in Vue JS?
So i am building an e-commerce website. The login and registration of users is handled in django templates. All the other part of the frontend is in VueJS. Is there a way that when i click on the login button on any page in my website, it takes me to the django login template? -
Allowing users to select which flow to roll back to django-viewflow
Hey all i have been using viewflow as the workflow engine in my django project. I wanted to know if it was possible to allow users to 'select' which flow they wish to roll back to if lets say an approval was rejected. Here , the director chooses 'Reject' , however it doesn't make sense to end the flow here , instead it should be a be a selectable 'roll back' , so that the the people down the line do not need to restart the entire process again. Here's what i have done so far : flows.py #director will approve or dont approve approve_by_director = flow.View( UpdateProcessView, form_class=DirectorApproveForm, task_title="Approval By Director" ).Permission("cash.director" ).Next(this.check_director) check_director = flow.If( cond=lambda act: act.process.director, task_title="Processing" ).Then(this.send).Else(this.justification) #justifications for the roll back. justification = flow.View( JustificationView, task_title="Justifications for Roll Back" ).Assign(lambda act: self.request.user ).Permission(auto_create=True ).Next(this.roll_back) roll_back = flow.Handler(this.roll_back_call).Next(this.approve_by_preparer) ##<---- here , i am just sending it back to the 'preparer' , however it would be great if this could be dynamic! end = flow.End() def roll_back_call(self, activation): esig = ESignatures.objects.filter(paymentVoucherProcess = activation.process).filter(voided = False) docu = Attachment.objects.filter(paymentVoucherProcess = activation.process).filter(voided = False) if len(esig) > 0 : for sig in esig: sig.voided = True sig.save() if … -
In django rest api An attempt was made to access a socket in a way forbidden by its access permissions
I was trying to do a "POST" request but getting this WinError 10013 Socket issue in my django api. I can do the "GET" request successfully but why i am getting this error on post request. OSError: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions "POST /api/v5/users/email/ HTTP/1.1" 500 177849 -
Search filtering from other paragraph models django
My search form works when typing words that are pulled from the description models.py, but I want to add another separated description called "the space" and display the text searched same as the in the description, I've tried several combinations code. This is my current code. In my views.py: # Keywords description if 'keywords' in request.GET: keywords = request.GET['keywords'] if keywords: queryset_list = queryset_list.filter(description__icontains=keywords) # space description if 'keywords' in request.GET: keywords = request.GET['keywords'] if keywords: queryset_list = queryset_list.filter(the_space__icontains=keywords) In models.py: description = models.TextField(blank=True) the_space = models.TextField(blank=True) context = { 'values': request.GET } In my html: <input type="text" name="keywords" class="form-control" placeholder="Keyword (search words)"> -
Как правильно реализовать ajax рендер модели в Django? [closed]
Есть страница с мероприятиями и некоторое количество фильтров, хочется сделать фильтрацию без перезагрузки страницы. Только учусь и задумался над тем правильно ли я собираюсь делать реализацию AJAX в CMS Wagtail а Django. Как я понял рендер делается не силами шаблона а уже javascript. Мой план 1. Делаю view возвращающую json 2. Обрабатываю JSON и генерирую HTML 3. Profit Вопрос в том что мне кажется что можно рендер сделать силами шаблона django. Просьба описать правильный workflow в этом случае и на что обратить внимание -
Django - upload_to dynamic path from different models
I'm trying to use ImageField upload_to to save the image in organize manner, but I cannot figure out if this is possible or how to. I'm trying to have this folder hierarchy inside media: Book-title Chapter 1 img1 img2 Chapter 2 img1 Models: class Book(models.Model): title = models.CharField(max_length=250, unique=True) slug = models.SlugField(max_length=250, unique=True) author = models.ManyToManyField(Author) chapter = models.ManyToManyField(Chapter, related_name='books') def image_dir_path(instance, filename): chapter = instance.slug return os.path.join(chapter, filename) class Chapter(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=130, unique=True) slug = models.SlugField(max_length=150, unique=True, blank=True) picture = models.ImageField(upload_to=image_dir_path) created_at = models.DateField(auto_now_add=True) I'd like to have something like this, so I can use the book title to build the path: def image_dir_path(instance, filename): book = instance.book.slug chapter = instance.slug return os.path.join(book, chapter, filename) This do not work, instance it's only related to the class where you call image_dir_path. It's something similar possible? -
Django rest framework, serializer serializer method field doesn't save changes to db?
I have a DRF API which contains a field that's being set in the serializer: class KnownLocation(models.Model): latitude = models.FloatField(name="Latitude", verbose_name='Latitude', unique=True, max_length=255, blank=False, help_text="Enter the location's Latitude, first when extracting from Google Maps.", ) longitude = models.FloatField(name="Longitude", verbose_name="Longitude", unique=True, max_length=255, blank=False, help_text="Enter the location's Longitude, second when extracting from Google Maps.", ) elevation = models.FloatField(name="elevation", help_text="Enter the location's ~Sea Level~ elevation, or Leave empty for auto-fill " "by me :). ", verbose_name="Elevation in meters", blank=True, default=DEFAULT_VALUE ) And the serializer: class KnownLocationSerializer(HyperlinkedModelSerializer): date_added = DateTimeField(format="%d-%m-%Y", required=False, read_only=True) elevation = SerializerMethodField() def validate_elevation(self, value): """ Validate that elevation of location has been updated already. """ if value is None or 1: raise APIException.elevation.throw() return value def get_elevation(self, obj): """ This method, which is connected to SerializerMethodField, checks if the object's elevation value exists, if not, it fetches it. """ elevation = obj.elevation if elevation is None or 1: elevation = get_elevation(lat=obj.Latitude, lon=obj.Longitude) elevation = round(elevation) return elevation pass The method works and fetches the elevation, yet, it doesn't save it to the DB. did I miss that part in the docs? so, how can I save it to the DB, using save didn't work for me: def save(self, **kwargs): latitude, … -
Django User-Interests App and its database Model design
I'm am building a django app which takes user Interests as inputs. Now I have 2 Questions - First is that, what model should I use, should I just add a field to user model or a separate Interest Model and link via Foreign Key? I know the former design is bad, and so I.m trying latter one, I'm having a hard time in Django to create Interest Model and its view to save the user interests. Any help is appreciated. -
Django Rest Framework: @Action Route with same url_path as Viewset
I want to POST to a DRF Viewset Detail Route. is this possible? I know with DRF you can override the Create field, but this won't allow you to access the detail route. Here's what I want to accomplish, notice the IS_THERE_A_WAY_TO_DO_THIS: class FooViewSet( mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet ): """ Foo-related viewsets. """ permission_classes = [IsAuthenticated] queryset = models.Foo.objects.all() serializer_class = serializers.FooSerializer @action( methods=["post"], detail=True, permission_classes=[IsAuthenticated], url_path="", <-- IS_THERE_A_WAY_TO_DO_THIS? Normally this wont work. url_name="foobar", ) def foobar_process(self, request, pk=None): pass -
Django + Bokeh: How to pass (a large set of) model objects to bokeh server app?
I'm new to both Bokeh and Django, so bear with me please. I have a bokeh app written and rendering through Django (I am able to navigate to the website, and pull up my bokeh app, which right now reads from a local CSV to render plots). I have since set up models in Django, and a table holds the same data as the CSV. Based on the URL that a user of the (future) Django website navigates to, I can filter out the QuerySet (objects of interest) from the database (sqllite), but now I'm stuck. How do I pass it to the bokeh app? I do not want to read from a csv. Here are the options I've come up with Include it in the request arguements: I can't do this (see bigreddot's comment here), my set of objects is large (i.e. I can covert it to a dataframe, and then to a string, but again, too large. script = server_document(url=request.build_absolute_uri(), arguments={'data_input': df') I can try to read from the sqllite database/Django ORM within the app, but this seems like overkill. I literally need to read the data once, when the page is first loaded. No updates to the … -
After a comment is posted and I try to like it, ajax lags and doesn't work immediately
I have a comment liking system in a Django website I'm building, where when a comment is liked, an ajax function is called. However, I've found that right after I post a comment, and try to like my own comment, the request.is_ajax() == FALSE instead of TRUE like it normally is. After a few minutes, and I reload it, the like button works fine. Is there an explanation for this, or has anyone encountered something similar? What was your solution? I'll put my code underneath in case it's relevant, but it's strange to me because it normally works well, it's only when I try to like a comment I just posted that it glitches out. AJAX: $('#comment-form').submit(function(event){ event.preventDefault(); $.ajax({ type: 'POST', url: $(this).attr('action'), data: $(this).serialize(), dataType: 'json', success: function(response) { $('.comments-section').html(response['form']); $('.reply-link').click(function(event){ event.preventDefault(); $(this).parents('.parent-comment').next('.replies').fadeToggle(); }) $('textarea').val(''); console.log('work') }, error: function(rs, e) {console.log(rs.responseText)} }) }) VIEWS.PY: @never_cache @login_required(login_url='login') def change_comment_like(request, pk): comment = Comment.objects.get(pk=pk) print(comment) print(request.method) print(request.is_ajax()) if request.method=='POST' and request.is_ajax(): print('work') user = request.user liked = False if user in comment.likes.all(): comment.likes.remove(user) else: comment.likes.add(user) liked = True comment.save() print(comment) return JsonResponse({'liked': liked}) return redirect('post_detail', pk=comment.post.pk) -
django rest framework serializer field validation when creating and updating instance
I have a Django application which I create a new instance or update an existing one in same view function. If instance_id is not give, so I create object, else I update data of existing object using instance_id. My views.py file is: def insert_update_country(request): country_serializer = serializers.Country(data=request.data) if country_serializer.is_valid(): country_id = country_serializer.validated_data.get('country_id', None) country_name = country_serializer.validated_data.get('country_name', None) country_code = country_serializer.validated_data.get('country_code', None) country, is_created = models.Country.objects.update_or_create( id=country_id, defaults={ 'country_name': country_name, 'country_code': country_code, } ) return Response( { 'Message':_('CHANGES_HAVE_BEEN_SAVED_TO_DATABASE'), 'Succeed': True }, status=status.HTTP_200_OK ) else: return Response( { 'Message': country_serializer.errors, 'Succeed': False }, status=status.HTTP_400_BAD_REQUEST ) The problem is even if I am doing an update on an existing instance, the serializer throw error as some fields must be unique. In my example when updating a country_name due to a typo, it says an instance with this country_code exists. The reason I have found in similar questions is: Django REST Framework (DRF) expects a POST request to only create new instances. I don't want to change my request method, it should be POST. How can I change my serializer to say if country_id is None, means I am creating new instance, so do the unique validation. Otherwise if country_id is not Node, means … -
How can i get image of Profile model, in my Post model
Here is two model Profile and Post. How can i get image from Profile model in my Post model? -
Add row dynamically in django formset
In my django app I have two models i.e Player and Team which are connected by many to many relatioship. To add the data dynamically in my tables I want to use javascript to add Add row or Remove Row button in my forms but unable to do so. Here are the details: Models.py class Player(models.Model): pname = models.CharField(max_length=50) hscore = models.IntegerField() age = models.IntegerField() def __str__(self): return self.pname class Team(models.Model): tname = models.CharField(max_length=100) player= models.ManyToManyField(Player) def __str__(self): return self.tname Forms.py class PlayerForm(forms.Form): pname = forms.CharField() hscore= forms.IntegerField() age = forms.IntegerField() PlayerFormset= formset_factory(PlayerForm) class TeamForm(forms.Form): tname= forms.CharField() player= PlayerFormset() Views.py def post(request): if request.POST: form = TeamForm(request.POST) form.player_instances = PlayerFormset(request.POST) if form.is_valid(): team= Team() team.tname= form.cleaned_data['tname'] team.save() if form.player_instances.cleaned_data is not None: for item in form.player_instances.cleaned_data: player = Player() player.pname= item['pname'] player.hscore= item['hscore'] player.age= item['age'] player.save() team.player.add(player) team.save() else: form = TeamForm() return render(request, 'new.html', {'form':form}) new.html <html> <head> <title>gffdfdf</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="/static/jquery.formset.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <form id="myForm" action="" method="post" class=""> {% csrf_token %} <h2> Team</h2> {% for field in form %} {{ field.errors }} {{ field.label_tag }} : {{ field }} {% endfor %} {{ form.player.management_form }} <h3> … -
Copy many-to-many entries for new element
Django beginner here. I want to create a new row in a table and copy the references many-to-many entries from another row. I have the following models (simplified): class Missions(models.Model): player = models.ForeignKey(Players, null=True, on_delete=models.CASCADE) units = models.ManyToManyField( Units, through='MissionUnits' ) class MissionUnits(models.Model): mission = models.ForeignKey(Missions, models.CASCADE) unit = models.ForeignKey(Units, models.CASCADE) count = models.PositiveIntegerField() class Meta: constraints = [ models.UniqueConstraint(fields=['unit', 'mission'], name='unique_mission_units') ] as well as two tables where unit player are defined. So what I want to do is the following: I have an existing "Missions" entry with associated "MissionUnits" entries. I want to create a new "Missions" entry with the same "MissionUnits" as the old one The new entries should persist even if I delete the old "Missions" entry Of course I could select all the "MissionUnits" entries, and extract and copy the information in a for loop, but is there also a more direct and elegant way to do this? If I just assign the oldmission.units to newmission.units, will this copy the elements? -
Get Minimum value of Each Query in Filter
I have two tables 1 product and 2nd price.like this class Activity(models.Model): activityName = models.CharField(max_length=50 , null=False, blank=False) activityId = models.CharField(max_length=20, null=True, blank=True) class PerPersonTire(models.Model): activity = models.ForeignKey(Activity, on_delete=models.CASCADE) name= models.CharField(max_length=100 , null=True , blank=True) minNumerofParticipents = models.IntegerField(default=0) price=models.IntegerField(default=0) Now case is in every activity have many price in foreign key. So when I Query on Activity I need minimum price from that table aswell. like Activity.object.all() I need here minimum price of each activity from price table as well. Any help regarding this would be highly appreciated. -
Django enctype=multipart/form-data on localhost returns white screen
I am running django on a pipenv virtual machine on my MacBook on localhost:8000. I created a django form to upload an image with enctype=multipart/form-data. When clicking on submit, on all browsers, I get a white page. Checking the browsers network status, its a 400 error, and in Firefox I get: The character encoding of the plain text document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the file needs to be declared in the transfer protocol or file needs to use a byte order mark as an encoding signature. When removing the enctype, everything works fine - but of course the image isn't uploaded. The error seems to occur before any data manipulation on my side. On a remote development server, everything works fine with and without encoding - so it seems to be related to my development environment. Unfortunately I can't find any hints on why this error occurs. Does anybody have a hint or an idea on how to solve this? More Information Macbook Pro Catalina 10.15.3 Django 2.2 Running with the django internal server (manage.py runserver) -
Django Polls App Part 3 Template Syntax Error
I am new to Django and going through the tutorial of polls app. I am stuck on part 3 with Template syntax error. I have searched all related posts on stackoverflow but can not find the problem. Below are my files: Polls/Views.py: from django.shortcuts import render # Create your views here. from django.http import HttpResponse from django.template import loader from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] template = loader.get_template('polls/index.html') context = { 'latest_question_list': latest_question_list, } return HttpResponse(template.render(context, request)) def detail(request, question_id): return HttpResponse("You're looking at question %s." % question_id) def results(request, question_id): response = "You're looking at the results of question %s." return HttpResponse(response % question_id) def vote(request, question_id): return HttpResponse("You're voting on question %s." % question_id) Polls/models.py: from django.db import models # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text Polls/templates/polls/index.html: {% if latest_question_list %} <ul> {% for question in latest_question_list %} <li><a href="/polls/{{ question.id }}/">{{ question.question_text }}</a></li> {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} polls/urls.py: from … -
product weight in ebaysdk
how can i can get product weight ? I used trading api but most of weight of the products equal to 0. is there any way to get product weight all the time? I requested like this: response = api_trading.execute('GetItem' , {"ItemID":"184097524395",'DestinationPostalCode':'2940','DestinationCountryCode':'GB'}) -
Django: Unable to Write File from ModelForm on Apache and Mod_wsgi
I have a Django 3.0.3 site running on RHEL 7 and Apache using mod_wsgi. On my development machine (Windows) I am able to save a file via a FileField field type. However, when deploying on production (RHEL 7 and Apache using mod_wsgi) I get an "[ErrNo 13] Permission denied" error when trying to save the file. I have set folder permissions to drwxrwxrwx. for the MEDIA_ROOT folder for the apache user which is named "apache" in my instance (as confirmed by both calling getpass.getuser() within the program and also from the httpd conf settings. It is also the name listed on mod_wsgi.process_group on the Django debug page. I have included my relevant code and debug: Debug Environment: Request Method: POST Request URL: https://www.samplesite.com/samples/addpatient/ Django Version: 3.0.3 Python Version: 3.7.1 Installed Applications: ['samples.apps.SamplesConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'bootstrap3', 'django.contrib.staticfiles', 'notifications'] 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 "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/opt/djangoproject/djangoprojectenv3/lib/python3.7/site-packages/django/contrib/auth/mixins.py", line 52, in dispatch … -
Run Django server at Single Host IP address
I am trying to restrict Django server to single Host IP in Local PC. Initially I am running Django server at Host IP lets say 127.0.0.1. Again I am starting server at different Host IP 127.0.0.2 (in same PC) than mentioned in step1. Now I am able to browse my website at both IPs. But I need server should be working at last given host IP i.e 127.0.0.2 and old IP address shouldn't give response to any requests from 127.0.0.1 IP. IP address I have given here is just sample IPs. Note: I will not be restarting the server. -
How does the functionality of a function in has_object_permission differs when both return same Boolean value?
Recently I started to learn about permissions in Django rest framework, and I find below code a bit confusing. class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.owner == request.user I know that has_object_permission is linked to a specific instance and is called from get_object, but I don't know how it works under the hood. I mean if the condition is met, both returns True, but first one is ready-only and second one is update and delete. What puzzled me though is how one gives read-only access and second gives write and delete access under ceiling of same function? Please help me understand this. Thank you.