Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
E! Error: Database telegraf not found and failed to recreate
I try to develop a project in Django backend in ubuntu and I am using docker for backend and I am using influxdb with for database but after completing the code when I going for docker-compose up it showing error related to telegraf database like E! Error: Database telegraf not found and failed to recreate hook_telegraf | 2018-06-03T09:10:00Z E! InfluxDB Output Error: Response Error: Status Code [404], expected [204], [database not found: "telegraf"] and This is my telegraf.conf [[outputs.influxdb]] urls = ["http://influxdb:8086"] # required database = "telegraf" # required precision = "s" retention_policy = "rp_mps_24w" write_consistency = "any" timeout = "5s" username = "test" password = "test" [[inputs.nginx]] urls = ["http://localhost/server_status"] This is error repetadly coming on screen 2018-06-03T09:03:30Z E! Error in plugin [inputs.nginx]: error making HTTP request to http://localhost/server_status: Get http://localhost/server_status: dial tcp 127.0.0.1:80: getsockopt: connection refused hook_influxdb | [httpd] 172.19.0.1 - - [03/Jun/2018:09:03:30 +0000] "POST /write?db=telegraf HTTP/1.1" 404 69 "-" "telegraf" fc2f9f45-670c-11e8-801c-000000000000 618 hook_influxdb | [httpd] 172.19.0.9 - test [03/Jun/2018:09:03:30 +0000] "POST /write?consistency=any&db=telegraf&rp=rp_mps_24w HTTP/1.1" 404 69 "-" "-" fc3001c6-670c-11e8-801d-000000000000 635 hook_influxdb | [httpd] 172.19.0.9 - test [03/Jun/2018:09:03:30 +0000] "POST /query?q=CREATE+DATABASE+%22telegraf%22 HTTP/1.1" 403 99 "-" "-" fc30690d-670c-11e8-801e-000000000000 543 hook_telegraf | 2018-06-03T09:03:30Z E! Error: Database telegraf not found and failed … -
How to find out what load the server will sustain and how to develop a highly loaded project?
There is a server with such parameters: Operating system: Debian 7.11 x86 Memory RAM: 1024 MB SSD memory: 30000 MB CPU: 2x2.8 Ghz I want to develop a social network project. Ability to search by certain parameters, send messages, add photos, publish entries to the wall. While this is the maximum. I'm interested in how much the server can handle, how to optimize for this site, and at what load will have to distribute the site to several servers, and most importantly, how to do it. This should be taken into account immediately at the beginning of writing, or to re-design the project will be easy? At the beginning of the project there will be about 1000 visitors, in the future I plan about 5000. I wonder which server should be, how many servers, etc., because I do not know about large projects. -
get a multiple choice queryset in Django view and save it
I have a multiple choice field with a foreign key. I want to save which keeper was attending a training session and I want to list all keepers as a multiple choice field. class AddAttendance(forms.ModelForm): attendanceKeeper = Attendance.objects.only("keeper","present").all() keeperValues = Attendance.objects.values_list("keeper__id", flat=True).distinct() keeper = forms.ModelMultipleChoiceField(widget=forms.widgets.CheckboxSelectMultiple, queryset=Keeper.objects.filter(id__in=keeperValues, status=1)) class Meta: model = Attendance fields = ('keeper',) def __init__(self, *args, **kwargs): super(AddAttendance, self).__init__(*args, **kwargs) self.initial["keeper"] = Keeper.objects.all() However my problem is, I am not familiar how to handle a queryset in the view and how to loop through it and to save every instance with the value True or False. I always get the value error that a queryset cannot be assigned "Attendance.keeper" must be a "Keeper" instance Can you help me how I access the queryset values and save them def new_attendance(request, team_pk, package_pk): if request.method == "POST": form = AddAttendance(request.POST) if form.is_valid(): for item in form: attendance = item.save(commit=False) attendance.keeper = get_object_or_404(AddAttendance.keeper) attendance.team = get_object_or_404(Team, pk=team_pk) attendance.created_date = timezone.now() attendance.save() return redirect(reverse('select_package', args=[package_pk, team_pk])) else: form = AddAttendance() return render(request, 'attendance/new_attendance.html', {'form': form}) -
Django 400 in test if changed HTTP_HOST
I'm trying to implement javascript rendering for requests from external sites. this is my view: class ShareWidgetRenderView(DetailView): model = ShareWidget content_type = 'application/javascript' template_name = 'widgets/share_widget_render.js' def get_object(self): self.object = get_object_or_404(ShareWidget, uuid=self.kwargs['uuid']) http_host = self.request.META.get('HTTP_HOST', None) if http_host: if http_host.startswith(self.object.website): return self.object return PermissionDenied() this is my test: class TestShareWidgetRenderView(TestCase): def setUp(self): self.user = UserFactory() self.widget = ShareWidgetFactory(website='google.com') def test_with_valid_host(self): resp = self.client.get( "/widgets/share/{}/".format(self.widget.uuid), HTTP_HOST="google.com" ) self.response_200(resp) this is part of my test settings: ALLOWED_HOSTS = ['*'] CORS_ORIGIN_WHITELIST = ( 'google.com', ) If I set localhost or 127.0.0.1 with any ports, my test passes, but if I set 'google.com', I get 400 response. What is wrong? -
How can I send data from the front by POST and save it on to db by django
enter image description here {% csrf_token %} SUBMIT -
How to filter query with comma separated parameters in Django
Please my question is not a duplicated, i have already search for it but with no consistent result. So i'm building a restfull api with djangorestframework I want this query like http://localhost:8000/api/products/?category_name_fr=shirt,shoes to find all products where category_name_fr contains shirt or shoes In order to do this after some googling i wrote a custom django filter class (MultiValueCharFilter) but the filter does not actually behave like i want. When i make a query like the above, it returns me all the product in ProductTable. But when i make a query like the bellow, the filtering is done properly http://localhost:8000/api/products/?category_name_fr=shirt Here is the source code of my filters.py file, the product class is ProductList from django_filters import rest_framework as filters from .models import ProductList from django_filters import Filter from django_filters.fields import Lookup class MultiValueCharFilter(filters.BaseCSVFilter, filters.CharFilter): def filter(self, qs, value): # value is either a list or an 'empty' value values = value or [] print(values) for value in values: qs = super(MultiValueCharFilter, self).filter(qs, value) | qs return qs class ProductListFilter(filters.FilterSet): min_price = filters.NumberFilter(name="price", lookup_expr='gte') max_price = filters.NumberFilter(name="price", lookup_expr='lte') category_name_fr = MultiValueCharFilter(name="category_name_fr", lookup_expr='icontains') category_name_en = MultiValueCharFilter(name="category_name_en", lookup_expr='icontains') collection_name_fr = MultiValueCharFilter(name="collection_name_fr", lookup_expr='icontains') collection_name_en = MultiValueCharFilter(name="collection_name_en", lookup_expr='icontains') name_en = MultiValueCharFilter(name="name_en", lookup_expr='icontains') name_fr = MultiValueCharFilter(name="name_fr", … -
Django - Checking database for session variable
Somewhat new Djangoer here. A (hopefully) quick question. Is it possible to check is another user is active at the moment? My site does not have logins in the traditional sense; there is no authentication. Users are assigned a randomly generated username, stored in their session whilst on the website, and can interact with the website under that username. I would like other users to be able to view these interactions and check if the user who made them is still active or is offline (their session has ended). -
DJango: forms errors: errors vs error_messages
In DJango forms. I have found two sets of errors in the form object 1) errors { as Errordict object} and 2) error_messages {as dict object) errors contains _all_ and individual error messages for each field. while error_messages contain messages whose code='something' etc is mentioned Is this is a new feature -
Django Celery autoretry_for and retry_policy
we're using django 1.10, celery 4.1.0 I noticed that when sending 'autoretry_for' parameter as job setting and 'retry_policy' to apply_async(), the retry policy is totally ignored. instead, it uses the 'default_retry_delay' and the default max retry, which is 3. for example: job settings: 'default': { 'soft_time_limit': 10, 'default_retry_delay': 10, 'autoretry_for': ('billiard.exceptions.SoftTimeLimitExceeded', 'app.utils.exceptions.FlowInternalServerErrorException',), 'on_retry': 'app.tasks.common_tasks.on_task_retry', 'celery_countdown': 0, 'expires': 86400, 'retry': True, 'retry_policy': { 'max_retries': 1, 'interval_start': 0, 'interval_step': 0.2, 'interval_max': 0.2, }, when the task is executed and it receives the 'FlowInternalServerErrorException' as in the 'autoretry_for', it will ignore the 'retry_policy' setting and will use 3 max retries and 10 seconds between retries. Is there a way to use the 'retry_policy' when facing one of the 'autoretry_for' exceptions? Thanks -
Django Choicefield based on User model but restricted as per userprofile field
I am working on a hard django project and I am stuck again. I have a field in the userprofile which is called troop: class UserProfile(models.Model): scout_username = models.OneToOneField(User, on_delete=models.CASCADE) Group_Choice = Groups.Scout_Groups() troop = models.SlugField(max_length=27, choices=Group_Choice, default='None', blank=False) date_of_birth = models.DateField(default=date.today) def __str__(self): return '%s'% (self.scout_username) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) Then I have a form which fills in data which is sent to my stData model. Within the form the user can choose to add details about another user. Except they can only add details to another user who has the same troop details. forms.py from django import forms from leaders.models import stData from django.contrib.auth.models import User from accounts.models import UserProfileManager, UserProfile #the choice list which would ideally contain the user's username #on the right and the link to the User's object on the left. #(Left and right corresponding to the position within the tuple) st_username_list=[ (None, 'Choose a user'), ] class BadgeForm(forms.ModelForm): def set_user(self, user): global st_username_list troop = user.userprofile.troop userprofile = UserProfile.objects.all() selected_st = userprofile.filter(troop=troop) #for every user within select_st, add them to the choice list as a tuple so the active user can select them for st in selected_st: username … -
Django-searchbar package use in Front-End
I'm quite new to Web Develpment and I've been trying to create a simple search bar that can filter the results of a single page, not the whole website. It's a contact list and I want to find in that page the contact I want, if that makes it more clear. Making a query I believe?. I noticed that there is a package called django-searchbar that pretty much makes the funcionality way easier, but their GitHub says nothing about how to implement it in an actual search bar at the front-end of a site. Search Bar view def searchbar(request): search_bar = SearchBar(request, ['name', 'last_name']) #When the form is coming from posted page if search_bar.is_valid(): my_name = search_bar['name'] Front-End Page navbar <nav style='opacity:0.3 !important;'> <div class="nav-wrapper"> <form> <div class="input-field" style='background-color:white !important;'> <input id="search" type="search" placeholder='Search Contact' action='post' required> <label class="label-icon" for="search" ><i class="material-icons" style='color:black;'>search</i></label> <i class="material-icons">close</i> <div id="searchResults" ></div> </div> </form> </div> </nav> -
Update ManyToManyField() with a queryset, is it possible with django ORM?
Hello Awesome People! I will try to make my question simple as much I can. So is it possible to avoid the for loop in the following code? for instance in Model.objects.filter(done=True): instance.field_name.add(*queryset) I want to update a ManyToManyField inside a queryset. Basically I'm just asking If I can do something like Model.objects.filter(done=True).update(field_name__add=*something) -
django : Passing an array from javascript frontend to python backend using django
The user will key in a series of numbers in javascript frontend which will be appended into an array, this array would then be used for calculation in python backend. How can I get this array into the Python backend? (please provide an example if possible as I am new to coding) -
Django: Getting the offset of an object in a QuerySet
I have two models, one is a question text and the second is a user- and question-specific answer. I a user has answered many questions, given a question, how can I find the index of the respective answer? Index meaning the number of previous answers/the position of the given answer. More specifically, when I query the following: from django.db import models from django.conf import settings class Question(models.Model): body = models.TextField() class Answer(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE) question = models.ForeignKey(Question, models.CASCADE) answer = models.TextField() def getIndexOfAnswer(user, question): answer = user.answer_set.filter(user=user, question=question).all().order_by("pk") return answer.???index()??? how can I get the index of an answer for a given user (say, ordered by PrimaryKey)? -
I need help in 'Django Function Based Detail View'
I know how to get detail view of something by 'pk' and 'slug'. like: views.py def Detail_Views(request,pk): try: form = employeeModel.objects.get(pk=pk) except: raise Http404('Page Doesnt Found') return render(request, 'detail_view.html',{'form':form}) urls path('<int:pk>',views.Detail_Views) But now im defining a Pay Slip Management website and in my models.py i have field called employee_id where values are like Emp001,Emp002 etc. So, i want to get Details Views with employee_id parameter! But dont know how to define the urls and views.Please guide me. -
How to import SystemLogType in onvif - python
I am using onvif - python (ONVIF Client Implementation in Python). I am writing a line of code as : obj = mycam.devicemgmt.GetSystemLog({'Logtype': 'System'}) Here mycam is a camera object. It gives an error as System must be SystemLogType value, not a string. (See docs of GetSystemLog). I want to know that how do i import SystemLogType or how do i write above line so as to make it work correctly. Thanks. -
Heroku- 10k Row limitation
Does Heroku Database 10k row limitation applicable for a single app or for a single Free account ? If I am making multiple apps having different databases then the row limitation will divide in all or 10k per app database? -
Unable to import 'django.contrib'
I am using VS code to make a django app. What is this error and how to remove this. Please help. Error- [pylint] E0401: Unable to import 'django.contrib' https://i.stack.imgur.com/KGBOH.jpg -
Is it possible to call a models field with a string ? Access a class member variable using string?
Suppose I have a model like this class modelEmployee(models.Model): employee = models.ForeignKey(modelEmployee, on_delete=models.CASCADE,null=True,default=None,blank=True) introduction = models.CharField(max_length=1000, unique=False,default="") imageA = models.ImageField(upload_to='images/', default='images/patient_images/blank.jpeg') I know I can call imageA field like this inst = modelEmployee.objects.get(id=12) inst.imageA.save(content = someContent,name=someName) Now suppose I receive the imageA field dynamically Is there a way for me to call the field imageA like this field = "imageA" inst.[field].save(content = someContent,name=someName) -
Sorting a dictionary by keys no longer shows the values
I have this dictionary: analytics = {datetime.datetime(2018, 4, 1, 0, 0): {'clicks': 5049, 'month': datetime.datetime(2018, 4, 1, 0, 0)}, datetime.datetime(2018, 3, 1, 0, 0): {'clicks': 592, 'month': datetime.datetime(2018, 3, 1, 0, 0)}, datetime.datetime(2018, 6, 1, 0, 0): {'impressions': 2159, 'clicks': 223, 'month': datetime.datetime(2018, 6, 1, 0, 0)}, datetime.datetime(2018, 5, 1, 0, 0): {'impressions': 32747, 'clicks': 4184, 'month': datetime.datetime(2018, 5, 1, 0, 0)}} I want to sort it by date, which I do using: analytics = sorted(analytics, key=lambda k: k) However, while this does sort the dictionary, it removes everything except the key. Any idea why and how to solve it? -
Showing binary code probably in place of Image?
[ <a class="fancybox" href="{{ obj.image.url }}"> <img src="{{ obj.image.url }}" title="{{ obj.description }}" alt="{{ obj.image.name }}" style="width: 100%"> </a> ]1 I have tried all the possibilities in href attribute, help me? -
Django filter by condition
I have a queryset that I want to paginate through alphabetically. employees = Employee.nodes.order_by('name') I want to compare the first letter of the employee's name name[0] to the letter that I am iterating on. - but I don't know how to filter by employees_by_letter = [] for letter in alphabet: employees_by_this_letter = employees.filter(name[0].lower()=letter) employees_by_letter.append(employees_by_this_letter) """error -- SyntaxError: keyword can't be an expression""" I suppose I could iterate through each employee object and append a value for their first letter... but there has to be a better way. -
The field post.Post.user was declared with a lazy reference to 'draft1.myuser', but app 'draft1' doesn't provide model 'myuser'
I'm trying to change my user model and getting this error on all my instances where I refer to settings.AUTH_USER_MODEL in my model fields: ValueError: The field account.EmailAddress.user was declared with a lazy reference to 'draft1.myuser', but app 'draft1' doesn't provide model 'myuser'. The field admin.LogEntry.user was declared with a lazy reference to 'draft1.myuser', but app 'draft1' doesn't provide model 'myuser'. The field comment.Comment.has_downvoted was declared with a lazy reference to 'draft1.myuser', but app 'draft1' doesn't provide model 'myuser'. The field comment.Comment.has_upvoted was declared with a lazy reference to 'draft1.myuser', but app 'draft1' doesn't provide model 'myuser'. The field comment.Comment.user was declared with a lazy reference to 'draft1.myuser', but app 'draft1' doesn't provide model 'myuser'. The field comment.CommentScore.user was declared with a lazy reference to 'draft1.myuser', but app 'draft1' doesn't provide model 'myuser'. ... Here's the relevent code: draft1/models.py class MyUser(AbstractBaseUser,PermissionsMixin): first_name = models.CharField(_('first name'),max_length=30 , unique=True) USERNAME_FIELD = 'first_name' settings.py AUTH_USER_MODEL = 'draft1.MyUser' Any idea what the problem is? -
add a list to dictionary django
how can i pass a list of files names to a dictionary in Django views and display all the files under this directory in my HTML page? here is what i am trying to achieve views.py def showDocuments(request,*args,**kwargs): courses = Course.objects.all() documents = Document.objects.all() context = { "documents" : documents , "courses" : courses, "files" : [], } if request.POST: if Document.objects.filter(courses__exact=request.POST["course"]).exists(): directory = os.getcwd()+"/frontend/documents/documents/"+request.POST["course"]+"/" contents = os.listdir(directory) for item in contents: if os.path.isfile(os.path.join(directory, item)): context["files"].append(item) print(context["files"])#this here will show the list of files inside the directory else: print("there is no files for this course yet!") return HttpResponseRedirect(reverse('files:dashboard')) #print(context["files"]) # it shows an empty list return render(request , 'dashboard.html' , context ) dashboard.html <form method="POST" action="." > {% csrf_token %} <select id="crs" class="custom-select custom-select-sm" name="course"> <option selected>Open this select menu</option> {% for obj in courses %} <option value="{{ obj.courseName }}" name="course">{{ obj.courseName }}</option> {% endfor %} </select> {% buttons %} <button type="submit" class="btn btn-success">Success</button> {% endbuttons %} </form> {% if files %} <ul> { % for file in files % } <li>{{ file }}</li> { % endfor % } {%endif%} -
Strava Api bad request
We need to get segments on Istanbul so we have to send geographical coordinates https://www.strava.com/api/v3/segments/explore?bound=41.008238, 28.978359&access_token= and we get Bad Request error. Here stravalib https://pythonhosted.org/stravalib/_modules/stravalib/client.html#Client.explore_segments https://developers.strava.com/docs/reference/#api-Segments-exploreSegments