Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
FilterSet in two models
If I say I have a three model like this class Tag(models.Model): tag_name =models.CharField(max_length=50) class ItemType(models.Model): name = models.CharField(max_length=50) class ItemImage(models.Model): name = models.ForeignKey(ItemType, on_delete=models.CASCADE) image = models.ImageField(upload_to='item_image') tags = models.ManyToManyField(Tag) In addition I have implemented FilterSet according to type of item which is working well. But if I add filter method by tag it says Cannot resolve keyword 'tags' into field. Choices are: id, image, name In serializers file I used this class ItemTypeSerializers(serializers.HyperlinkedModelSerializer): images = ImageSerializers(source='image_set', many=True, read_only=True) tags = serializers.SerializerMethodField() def get_tags(self, tags): return TagSerializers(Tag.objects.filter(image__name__name=tags), many=True).data class Meta: model = ItemType fields = ('id', 'name', 'images', 'tags') read_only_fields = ('tags',) How can I FilterSet to project which filters by tags in filters.py I have used this code class TagFilter(FilterSet): tags = filters.CharFilter(method='tags_filter') class Meta: model = ItemType fields = ('tags',) def tags_filter(self, queryset, name, value): tag_names = value.strip().split(',') tags = Tag.objects.filter(image__name__name=tag_names) return queryset.filter(tags__in=tags) I know my Tag model is not connected to ItemType model but how can I add filter method to it? Thanks beforehand! -
Best way to get file list in dir sorted by added date
I have to delete the oldest file in dir when the newest added file exceed the used space limit. I don't know why the sorted list files = sorted(os.listdir(DIR), key=os.path.getctime) do not contain on first element the oldest file ( in this case file named 'file_1') code print('START: Cycle no. ', cycle) time.sleep(1) print('Saving {0} files. {1} MB each'.format(FILES_NUM, MB_FILE_SIZE)) i = 1 while (i < FILES_NUM): usage = psutil.disk_usage(DIR) used = usage.used // (2**20) # print('Uzyta pamiec: ', used) if (used < 50): # 50 MB print('Saving file_{}'.format(i)) with open("file_{}".format(i), 'wb') as f: f.write(os.urandom(FILE_SIZE)) else: files = sorted(os.listdir(DIR), key=os.path.getctime) print('Files list: ', files) os.remove(files[0]) print('Deleted oldest file: ',files[0]) i = i + 1 print('KONIEC: Cycle no. ', cycle) print('Deleting the content of the card...') results -
Where should server logs be kept?
I have a django webapp where lots of functions like online presence,chat messaging and other real time operations are going on.This is logging a lot of data in my daphne.log file. To give you an idea, within 5 minutes daphne.log file reached the size of 100kb when i am the sole person accessing the app.Certainly the daphne.log file will become huge when it will serve thousand of visitors per day. This will consume a lot of memory on my server.What should be the best approach to manage this kind of situation? My thought is to have a some sort of program that will keep clearing daphne.log file in regular intervals but this nullifies the purpose of logs. daphne.log file is present at /home/user/django_project/logs/daphne.log What should i do if i want to retain logs? P.S: I have deployed my django app using Supervisor + Nginx + Postgresql + Daphne. -
pass zip file from unc to python code running inside docker
I have a python script running inside a docker container. This app does the loading of builds on to external hardware which is connected on the network. The builds are in zip format and are available in the local network share \\path\to\zip.zip. I am running a python script inside the docker container to trigger this loading zip file. The python script is simple. All it takes is >python load.py IP path_to_zip The script then unzips the contents and makes an ftp connection to the hardware and erases the existing contents, then loads the contents of the zip file. At the moment, I see that the docker container is not able to access the unc path. The script runs fine on a normal environment (without docker) I've tried it in different ways to resolve the issue 1.When I try giving the unc path from inside docker (attaching shell), I see that it cannot find the unc path I tried building the Docker container with the zip file in it so that it is available. But I do not see the contents getting uploaded to the hardware. I am not sure why. can someone suggest what is the best way to perform … -
Add related ForeignKey fields with serializer in Django REST Framework
I'm using Django 2.2 and Django REST Framework I have three models like class Plan(models.Model): name = models.CharField(_('Plan Name'), max_length=100) default = models.NullBooleanField(default=None, unique=True) created = models.DateTimeField(_('created'), db_index=True) quotas = models.ManyToManyField('Quota', through='PlanQuota') class Quota(models.Model): codename = models.CharField(max_length=50, unique=True) name = models.CharFieldmax_length=100) unit = models.CharField(max_length=100, blank=True) class PlanQuota(models.Model): plan = models.ForeignKey('Plan', on_delete=models.CASCADE) quota = models.ForeignKey('Quota', on_delete=models.CASCADE) value = models.IntegerField(default=1, null=True, blank=True) I have to get all quota and their value from PlanQuota in the plan serializer while getting a list of plans. I have the following serializer class PlanQuotaSerialier(serializers.ModelSerializer): class Meta: model = PlanQuota depth = 1 fields = ['quota', 'value'] class PlanListSerializer(serializers.ModelSerializer): plan_quota = PlanQuotaSerialier(read_only=True, many=True) class Meta: model = Plan depth = 1 fields = ['name', 'default', 'created', 'plan_quota'] But there is no plan_quota in the response. How can I add all Quota and their value for each plan in a single query (SQL JOIN)? -
uwsgi pidfile get deleted automatically
I have a nginx server setup with django and uwsgi. There are multiple django apps run simultaneously on different virualenvs, separate uwsgi processes on separate ports on which nginx listens to. The setup works alright. I use pidfile flag to stop uwsgi processes. When I start the any uwsgi server, pidfile is created and I can immediately restart without errors with the script provided below. After while when I come back to update the server, the pidfile is gone and the uwsgi process is still running. This makes this approach useless. project_A_uwsgi.ini: [uwsgi] master = true socket = /tmp/stripe_test_uwsgi.sock chmod-socket = 666 chdir = /home/ubuntu/TestProjects/ProjectA wsgi-file = /home/ubuntu/TestProjects/ProjectA/ProjectA/wsgi.py virtualenv = /home/ubuntu/TestProjects/ProjectA/venv vacuum = true enable-threads = true daemonize= /home/ubuntu/TestProjects/ProjectA/uwsgi.log project_A_server_restart.sh: #!/bin/sh DEPLOYMENT_PATH='/home/ubuntu/TestProjects/ProjectA' . ${DEPLOYMENT_PATH}/venv/bin/activate uwsgi --stop /home/ubuntu/TestProjects/project_A_uwsgi.pid uwsgi --ini /home/ubuntu/TestProjects/project_A_uwsgi.ini --pidfile /home/ubuntu/TestProjects/project_A_uwsgi.pid sudo service nginx restart What could be the reason for the pidfile to get deleted? how will I prevent that? -
How to organize multiple code repos with shared modules?
Recently we wanted to reorganize the code repos and now they are all in one. We have a web Backend and a mobile backend. They’re sharing the same database models and some common utils. For both the web backend and mobile backend, we already apply the app method and they are in different directory. We wanted to separate them into three git repos with different access permission: web backend, mobile backend, the common. It can benefit both the code code control and the deployment process. For example, we only need to restart the web backend server if there is new code in web backend. Are there any best practice recommendations? -
How to adapt django models?
I want to add models Room name = 'kimuk' current_player_number =1 this result Room name = '' , current_player_number =1 why reflect one parameter? -
How to implement web app Oauth Youtube API call for beginners
Are there any updated beginner tutorials on how to implement the Google OAuth 2.0 protocol so my web app can use the Youtube Data API? The Google quickstart documentation only goes through the console flow. I've tried the Oauth2.0 for Web Server Application guide, but it's it makes no sense to me and it's also in Flask. All guides I've followed from Google use deprecated packages. All the guides are also different from each other. This is code the achieves what I need. However, instead of using the Google authentication popup, it asks me to go onto the console. SCOPES = ['https://www.googleapis.com/auth/youtube.force-ssl'] API_SERVICE_NAME = 'youtube' API_VERSION = 'v3' class youtube_base: # Working auth code def get_authenticated_service(): flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file( CLIENT_SECRETS_FILE, SCOPES) credentials = flow.run_console() return build(API_SERVICE_NAME, API_VERSION, credentials=credentials) This is how I call the Youtube API in my web app: class YtAuthView(UserPassesTestMixin, UpdateView): model = Profile form_class = YtAuthForm template_name = 'yt_auth_update.html' def form_valid(self, form): client = youtube_base.get_authenticated_service() stats = get_channel_stats(client, self.object.youtube_channel_id) form.instance.yt_subscribers = stats['totalSubs'] form.instance.yt_views_avg = stats['viewsAverage'] form.instance.yt_views_median = stats['viewsMedian'] form.instance.yt_eng_rate = stats['engagementRate'] form.instance.yt_last_updated = stats['dataRecorded'] response = super(YtAuthView, self).form_valid(form) return response -
Django guardar un queryset?
Me gustaria saber como puedo guardar mi queryset en la base de datos: lo genero con values_list() me regresa: <QuerySet [(Decimal('133.22'),)]> Ahora mi duda es como lo guardo en mi Modelo en el fiel "bdata_superior": class Csr(models.Model): tarifa_cobro = models.ForeignKey(Tarifa_Sem, on_delete=models.CASCADE, null=True, blank=True) bdata_superior = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) data_inferior = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) Gracias por su ayuda. -
_DeadlockError in Django while starting server
A lot many times I encounter this error while starting python server. This also happens when I change any file and server boots up again. I've tried deleting the environment and re-creating the environment but still the same error persists. Python 3.5.2 (default, Nov 12 2018, 13:43:14) [GCC 5.4.0 20160609] on linux Django: 2.2.1 /home/satyam/Code/myproject/myproject_apps/invoice/services/excel_service.py changed, reloading. Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "/home/satyam/Code/environments/ebapps/lib/python3.5/site-packages/django/template/utils.py", line 66, in __getitem__ return self._engines[alias] KeyError: 'django' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.5/threading.py", line 914, in _bootstrap_inner self.run() File "/usr/lib/python3.5/threading.py", line 862, in run self._target(*self._args, **self._kwargs) File "/home/satyam/Code/environments/ebapps/lib/python3.5/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/satyam/Code/environments/ebapps/lib/python3.5/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/home/satyam/Code/environments/ebapps/lib/python3.5/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/home/satyam/Code/environments/ebapps/lib/python3.5/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/home/satyam/Code/environments/ebapps/lib/python3.5/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/satyam/Code/environments/ebapps/lib/python3.5/site-packages/django/contrib/admin/checks.py", line 79, in check_dependencies for engine in engines.all(): File "/home/satyam/Code/environments/ebapps/lib/python3.5/site-packages/django/template/utils.py", line 90, in all return [self[alias] for alias in self] File "/home/satyam/Code/environments/ebapps/lib/python3.5/site-packages/django/template/utils.py", line 90, in <listcomp> return [self[alias] for alias in self] File "/home/satyam/Code/environments/ebapps/lib/python3.5/site-packages/django/template/utils.py", line 81, in __getitem__ engine = engine_cls(params) File "/home/satyam/Code/environments/ebapps/lib/python3.5/site-packages/django/template/backends/django.py", line 25, … -
South migration in django
I added a new field in an existing model in django. Note that this app is already converted to south. To apply my new changes I ran these commands python manage.py schemamigration my_app --auto python manage.py migrate my_app This is giving an error like "Table 'database.south_migrationhistory' doesn't exist". So I try to migrate south. python manage.py syncdb python manage.py migrate south But this results in the same error "Table 'database.south_migrationhistory' doesn't exist". How do I solve this? -
Django model search won't return any values
I'm trying to create a search function that will return the corresponding values in the table based on the id or asset_name but it's not returning anything when I search for a valid id or asset_name. Is there something I'm missing in my code? Views.py def search(request): template = 'blog/home.html' query = request.GET.get('q') if query: results = Post.objects.filter(Q(id__icontains=query) | Q(asset_name__icontains=query)) else: results = Post.objects.filter(status="Published") context = { 'query': query } return render(request, template, context) class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] Urls.py urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('results/', search, name='search'), ] Home.html <form method="GET" action="{% url 'search' %}"> <input type="text" name="q" value="{{request.GET.q}}" placeholder="Search for project" /> <input type="submit" value="Search" /> </form> <tbody> {% for post in posts %} <tr data-href="linkToFile.pdf"> <td>{{ post.id }}{% if query %}&q={{query}}{% endif %}</td> <td><a href="{% url 'post-detail' post.id %}">{{ post.asset_name }}{% if query %}&q={{query}}{% endif %}</a></td> </tr> {% endfor %} </tbody> -
Django context value for home page
I have a model that takes a Boolean update from the admin. If the admin clicks it, the end user can or cannot access the a view. The problem is that the view is accessible through the home page which has a base file and it requires the id of the user to check against. I get this error NoReverseMatch at /home/ I am unable to understand how can I pass the context value to the base file. I don't want to create another view for as it's a base file. I tried context_processors but it gives me this error at the home.view int() argument must be a string or a number, not builtin_function_or_method I have two functions in context_processors, each has it's own characteristics. Here is the code settings.py TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'projectfiles.context_processors.emp_base_context', 'projectfiles.context_processors.lev_base_context', ],},},] models.py class Employee(models.Model): allowed = models.BooleanField(default=True) employee_name = models.OneToOneField(User, on_delete = models.CASCADE) employee_designation = models.CharField(max_length = 5) employee_department = models.CharField(max_length = 5) Annual_leave = models.PositiveSmallIntegerField(default=5) Sick_leave = models.PositiveSmallIntegerField(default=5) Casual_leave = models.PositiveSmallIntegerField(default=5) Half_pay = models.PositiveSmallIntegerField(default=5) Emergency_leave = models.PositiveSmallIntegerField(default=5) class Leave(models.Model): employee_leaves = models.ForeignKey(Employee, on_delete=models.CASCADE) leave_Type = models.CharField(max_length=25) leave_qty = models.PositiveSmallIntegerField(default=0) description … -
how to fix django-db-mailer SMS API language argument changing the language of the application
when we are applying language='ar' kwargs to the send_db_sms() API it will change the Language of the entire web application. from dbmail import send_db_sms send_db_sms( # slug which defined on db template slug='welcome', # recipient can be list, or str separated with comma or simple # string recipient='+79031234567', # All *args params will be accessible on template context { 'username': request.user.username, 'full_name': request.user.get_full_name(), 'signup_date': request.user.date_joined }, # Optional kwargs: language='ar', ) by giving language='ar',kwargs to the send_db_sms() function, it should not change the language of the entire web application. -
error is occured by delete function (django fbv)
I ran the deletion with the following function Deletion is succeeded but error occurred def todo_delete (request, pk): # template = 'todo / todo_confirm_delete.html' todo = get_object_or_404 (Todo, pk = pk) todo.delete () Profile.objects.filter (Q (user = request.user.id)). Update (uncompletecount = F ('uncompletecount') - 1) print ("todo", todo, delete ') return reverse_lazy ('todo: todo_list') error AttributeError: '__proxy__' object has no attribute 'get' thanks for let me know what is reason for error and how to fix -
Handle Nested Serializer Which is not part of model?
I want to use read/write nested serializer which is part of model being serialized., { "student_name": "Foobar", "department": 1, "custom_fields": [ {'field_name': 'Email', 'field_value': 'foo@mail.com'}, {'field_name': 'Roll No': 'fiel_value': '124'} ] } I in response above custom_fields is part of model Student., those fields will vary depends upon department passed. When i am trying like below. class CustomFieldSerializer(serializer.Serializer): field_name = serializers.CharField() field_value = serializers.CharField() class StudentSerializer(serializer.ModelSerializer): custom_fields = CustomFieldSerializer() class Meta: model = Student fields = ("student_name", "department", "custom_fields") serializer = StudentSerializer(instance=student) since custom_fields is not part of serializer am getting error like Student object has not attr called custom_fields. To prevent that error, The approach i follow is for read operation i made the field SerializerMethodField in to_representation and List Field in to_internal_value like below class StudentSerializer(serializer.ModelSerializer): class Meta: model = Student fields = ("student_name", "department") def to_repesentation(self, instance): self.fields['custom_fields'] = serializers.SerializerMethodField() return super().to_representation(instance) def to_internal_value(self, data): self.fields["custom_fields"] = serializers.ListField(child=CustomFieldSerializer) return super().to_internal_value() Is this right approach or is there any better alternative? -
How to setup my crontab in order to execute process_tasks in Django?
I decided to use a library for my Django project called django-background-tasks (link to the documentation: https://django-background-tasks.readthedocs.io/en/latest/). I want to deploy my Django application to a Linux server (Ubuntu 19.0.4). How should I write the crontab in order to call the command "process_tasks" every five seconds? Here Running a cron every 30 seconds is a workaround to achieve the seconds part, but since I am new to this part of the job (deploying and automation of process), how should I create my crontab file in order to achieve my desired purpose? Thank you in advance for any suggestion, if you need something more I would be happy to provide it to you. -
Amazon BeansTalk log time deploy Python Django
i use Aws Beanstalk and have issue when trying deploy new feature code in Python Django. It take so much time about 30min. I dont know why and i wish have any ideal how to check it. My question is : how to log time deploy in aws beanstalk?. Step by step running deploy in aws for find what take time deploy server. Thank you! -
How to get the location of user using observepoint API
I am looking for some help on how I can use the Observepoint API to get the location from where the Audit was created. I am using Django. Using the example on https://docs.api.observepoint.com/v2/web-audits/w43h2it5WmM2srcC2 This is my current code: payload = "{}" headers = { 'authorization': "api_key " + API_KEY} get_user_loc = 'https://api.observepoint.com/v2/web-audits/locations' response_loc = requests.request("GET", get_user_loc, data=payload, headers=headers) ping = response_loc.json() print(type(ping[1])) for x in ping: print(x["name"], " = ", x["label"]) This is giving me all the locations it has. mountain = Direct - Oregon, US west = Proxy - N. California, US eastern = Proxy - N. Virginia, US emea = Proxy - Dublin, Ireland apac = Proxy - Tokyo, Japan brazil = Proxy - Sao Paulo, Brazil london = Proxy - London, England germany = Proxy - Frankfurt, Germany singapore = Proxy - Singapore australia = Proxy - Sydney, Australia How do I get the exact current location and match it to one of these? -
How do I store membership information in a profile model that is tied to the default user model with foreignkey?
How do I store membership information in a profile model that is tied to the default user model with foreignkey? Will I be able to do so by using cusotomizing forms.py? veiws.py def signup(request): if request.method=="POST": form = SignupForm(request.POST) if form.is_valid(): # 입력한 값이 있을 경우 True를 반환 user = form.save() return redirect(settings.LOGIN_URL) else: # 입력한 값이 없을 경우 form = SignupForm() return render(request, 'accounts/signup_form.html',{ 'form':form, }) ex from django.contrib.auth.forms import UserCreationForm from django import forms class SignupForm (UserCreationForm): class Meta (UserCreationForm.Meta): fields = UserCreationForm.Meta.fields + ('email', 'phone') models.py class Profile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE) phone = models.CharField(max_length=20) address = models.CharField(max_length=100) completecount = models.IntegerField(default=0) uncompletecount = models.IntegerField(default=0) reputation = models.IntegerField(default=0) -
I am seeing a "GET /emp HTTP/1.1" 404 2159 on my terminal when I try to connect to the django server ...I am receiving a 404 page not found
I feel like my server can't render my views well because of some url configuration issues.It always render the message Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/emp Here is my project structure |--hrdjango |--employee |--migrations folder |--admin.py |--urls.py ... |views.py |--hrdjango ... |--settings.py |--urls.py views.py from django.shortcuts import render, redirect from .forms import EmployeeForm from .models import Employee # Create your views here. def emp(request): if request.method == "POST": form = EmployeeForm(request.POST) if form.is_valid(): try: form.save() return redirect('/show') except: pass else: form = EmployeeForm() return render(request,'index.html',{'form':form}) def show(request): employees = Employee.objects.all() return render(request,"show.html",{'employees':employees}) def edit(request, id): employee = Employee.objects.get(id=id) return render(request,'edit.html', {'employee':employee}) def update(request, id): employee = Employee.objects.get(id=id) form = EmployeeForm(request.POST, instance = employee) if form.is_valid(): form.save() return redirect("/show") return render(request, 'edit.html', {'employee': employee}) def destroy(request, id): employee = Employee.objects.get(id=id) employee.delete() return redirect("/show") employee/urls.py from .import views from django.contrib import admin from django.urls import path, include app_name = 'employee' urlpatterns = [ path('', views.emp, name='emp'), path('show',views.show, name='show'), path('edit/<int:id>', views.edit, name='edit'), path('update/<int:id>', views.update, name='update'), path('delete/<int:id>', views.destroy, name='destroy'), ] hrdjango/urls from django.contrib import admin from django.urls import include, path from employee import views urlpatterns = [ path('admin/', admin.site.urls), path('employee/', include('employee.urls')), path('', views.emp), ] I was expecting to see the … -
Monitor and Detect a change in Excel file and refresh location of the web page
I have an excel file where data is refreshing from third party application. Problem to solve: My DJANGO web application should monitor that excel file continuously and detect a change from that excel file. Whenever there is a change then particular location of web page should be refreshed. Could somebody please give suggestions to achieve this functionality? -
using axios post from react to django rest framework got 400 ( bad request) when posting objects contains empty strings
I don't get it why this is happening as long as i post an object with an empty string value in it will cause an error and the code snippet is the function that I called for posting values result from posting with empty string: https://i.ibb.co/jfhcQY8/1.png post with arbitrary values: https://i.ibb.co/CtZ2CKB/2.png addToServer(e) { console.log("item: " + this._input.value) if (this._input.value !== "") { var newItem = { "title": this._input.value, "content": "", //===>if it's empty string it will get a 400 error, however if i change to any non empty value, it will work "complete": false, }; console.log("item: " + newItem.title) console.log(newItem) axios.post("http://localhost:8000/api/todo/", newItem) .then(res => this.axiosGet()) .catch( err => console.log(err)) } this._input.value = ""; this._input.focus(); e.preventDefault(); } -
Recipe many ingredients DB design
I need to create a model in Django where I can store recipes. Each recipe must have at least one ingredient. To do so I need to assign each recipe to ingredient(s) table ids using select drop boxes.