Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Implement LiteSync on Django
I've tried to write sync sqlite database between 2 different Server but same app and DB. But when i turn on litesync.io in console, it doesnt synchronize the Django project with Django project in another server. I know it's wrong because i must configure it first in django project, but i've tried to change NAME of DATABASES into URI and it not work. I've tried it in console to execute query, it works, but not in Django Project. So, how to implement litesync on Django project? How to save data into Sqlite DB by URI? -
getting error : Reverse for 'detail' with arguments '(1,)' not found. 1 pattern(s) tried: [u'polls/<int:question_id>/'] in django
I am newbie here in django, when i run my app, I am getting this error Reverse for 'detail' with arguments '(1,)' not found. 1 pattern(s) tried: [u'polls/<int:question_id>/'] here i have uploaded my code for index.html and urls.py can you please check my code and help me to resolve this issue ? index.html {% if latest_question_list %} <ul> {% for question in latest_question_list %} {% if question.id %} <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li> {% else %} {% endif %} {% endfor %} </ul> {% else %} <p>No polls are available.</p> {% endif %} urls.py from django.conf.urls import url from . import views app_name = 'polls' urlpatterns = [ url('', views.index, name='index'), # ex: /polls/5/ url('<int:question_id>/', views.detail, name='detail'), # ex: /polls/5/results/ url('<int:question_id>/results/', views.results, name='results'), # ex: /polls/5/vote/ url('<int:question_id>/vote/', views.vote, name='vote'), ] -
Can we set min max restriction on form field in views. Django
Form's Integer field quantity = forms.IntegerField() I want to set the min_value and max_value on this field in views such as form.fields['quantity'].min_value = 0 It's possible to set the initial value using form.fields['quantity'].initial = 12 But the min value is not working. Can anyone help me with that. -
Where to put customized views that inherits from django-allauth?
I have a Django project that has one app (survey), so in my project's urls.py, I have: urlpatterns = [ ... path('accounts/', include('allauth.urls')), path('survey/',include(('survey.urls','survey'), namespace='survey')), ...] I am using django-allauth to provide the authentication mechanism. However, I inherited the SignupView that is in Django-Allauth like so: class MySignupView(SignupView): def form_valid(self.request): self.user = form.save(self.request) assignmentAttendance=AssignmentAttendance.objects.create(user=user, assignment=Assignment.objects.get(id=1), status=False) assignmentAttendance.save() assignmentAttendance = AssignmentAttendance.objects.create(user=user, assignment=Assignment.objects.get(id=2), status=False) assignmentAttendance.save() try: return complete_signup( self.request, self.user, app_settings.EMAIL_VERIFICATION, self.get_success_url()) except ImmediateHttpResponse as e: return e.response The additional process (in the override the form_valid) is to create data for another model in the survey app. I do not know the best place to put the class MySignupView, so I put it in the project's urls.py and then add its view to the urlpatterns: urlpatterns = [ ... path('accounts/', include('allauth.urls')), path('survey/',include(('survey.urls','survey'), namespace='survey')), path('accounts/signup', MySignupView.as_view(), name="account_signup"), ...] Doing this works, since my MySignupView is what is called when a user wants to signup instead of the SignupView from Django-allauth. Is there a better configuration for where to writing custom views and where to put them. If so, how should it be done? I am aware that Django-allauth has a default way for adding custom form by setting the ACCOUNT_FORMS in the settings.py. … -
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 …