Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Bring machine learning to live production with AWS Lambda Function
I am currently working on implementing Facebook Prophet for a live production environment. I haven't done that before so I wanted to present you my plan here and hope you can give me some feedback whether that's an okay solution or if you have any suggestions. Within Django, I create a .csv export of relevant data which I need for my predictions. These .csv exports will be uploaded to an AWS S3 bucket. From there I can access this S3 bucket with an AWS Lambda Function where the "heavy" calculations are happening. Once done, I take the forecasts from 2. and save them again in a forcast.csv export Now my Django application can access the forecast.csv on S3 and get the respective predictions. I am especially curious if AWS Lambda Function is the right tool in that case. Exports could probably also saved in DynamoDB (?), but I try to keep my v1 simple, therefore .csv. There is still some effort to install the right layers/packages for AWS Lambda. So I want to make sure I am walking in the right direction before diving deep in its documentation. -
Django admin panel Datepicker not working
I am using daterangefilter to filter result according to dates but my datepicker is not working.Its showing datepicker icon but not working. I tried to reinstall daterangefilter as well as django-suite(seen somewhere while searching for the solution) to identify the problem but it is in same state. list_filter = ['company', 'status', 'published', 'dont_publish',('created_at', DateRangeFilter)] -
How can in filter by more than one value of same field at django admin using list_filter?
i have field "car" that contains values "Benz, Nissan, Kia" using ==> list_filter ["car"] how can i filter by Both values like "Nissan" and "Kia" . Both not one of them Car objects -
SSO with Django and Active Directory
I have a web application developed using Django. It's hosted remotely on AWS but deployed to clients using their local networks. At the moment users just sign in using the standard django authentication approach. They each have their own usernames, passwords specific to the app, etc. I would like to be able to provide single sign on, so users who are already authenticated by active directory will be logged directly to the site. Is this possible with an app hosted on AWS? I assume there would have to be some kind of hook into AD? I have read this answer and this answer, but they appear to work for intranet apps only. -
Problem with running Django with nginx and uwsgi
I'm trying to install a new server, and I can't run Django with nginx and uwsgi. I receive an error "502 Bad Gateway" and there are messages on the error log which I don't understand: 2019/07/20 10:50:44 [error] 2590#2590: *1 upstream prematurely closed connection while reading response header from upstream, client: 79.183.208.33, server: *.speedy.net.3.speedy-technologies.com, request: "GET / HTTP/1.1", upstream: "uwsgi://unix:/run/uwsgi/app/speedy_net/socket:", host: "3.speedy-technologies.com" I have 4 websites and here is the main (default) configuration file: server { listen [::]:80 default_server; listen 80 default_server; server_name *.speedy.net.3.speedy-technologies.com speedy.net.3.speedy-technologies.com; access_log /var/log/nginx/speedy-net.access.log; error_log /var/log/nginx/speedy-net.error.log; client_max_body_size 50M; root /home/ubuntu/speedy-net/speedy/net/static_serve/root; try_files $uri @uwsgi; location @uwsgi { include uwsgi_params; uwsgi_pass unix:/run/uwsgi/app/speedy_net/socket; } location /admin/ { auth_basic "admin site"; auth_basic_user_file /etc/nginx/htpasswd_admin; include uwsgi_params; uwsgi_pass unix:/run/uwsgi/app/speedy_net/socket; } location /static { alias /home/ubuntu/speedy-net/speedy/net/static_serve; access_log off; # expires max; gzip on; gzip_min_length 1100; gzip_buffers 4 32k; gzip_types text/css text/javascript text/xml text/plain text/x-component application/javascript application/x-javascript application/json application/xml application/rss+xml font/truetype application/x-font-ttf font/opentype application/vnd.ms-fontobject image/svg+xml; gzip_vary on; gzip_comp_level 6; } } And: [uwsgi] project = net chdir = /home/ubuntu/speedy-net home = %(chdir)/env module = speedy.%(project).wsgi:application plugins = python3 master = true processes = 4 chmod-socket = 666 vacuum = true uid = ubuntu gid = ubuntu touch-reload = /run/uwsgi/app/speedy_%(project)/reload I tried to test with sudo … -
How to access files that are outside of a django project from a template
I am working on a python project where my raspberry pi sends frames from a camera to my server. The server displays these frames as a video and when movement gets detected it saves the video as '/mnt/cameras/"year-month-day"/"hour-min-sec".webm. This all works fine, but I can't get these saved video's to work on my web-page since they are not inside of my project. I know for sure that I can play these video's because when I put them in my 'media' folder it does work. In my settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(REPOSITORY_ROOT, 'static/') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(REPOSITORY_ROOT, 'media/') CAMERAS_URL = '/cams/' CAMERAS_ROOT = '/mnt/cameras/' In my urls.py: from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.camerapage, name="cameraspage"), path('camera<cam_number>',views.livefe, name='camera'), path('browse/',views.browsepage, name='browse'), ]+static(settings.CAMERAS_URL, document_root=settings.CAMERAS_ROOT) In my views.py: videos_path = "/mnt/cameras" def browsepage(request): class Video: path = '' title = '' def __init__(self,path,title): self.path = path self.title = title def __str__(self): return self.title class Date: date = '' path = '' videos = [] def __init__(self,path,date): self.path = path self.date = date def __str__(self): return self.date dates = [] for dir_or_file in os.listdir(videos_path): date_folder_path = os.path.join(videos_path,dir_or_file) if … -
how to set the order of row by drag and drop in python django with jquery and save that order in the database
want to change the row by drag and drop and also save the order in the database accordingly Name L Group C Group Order Image Source Data Source 'show data od labor in tablerow' {% for labor in labours %} -
django+heroku+S3 storage only content embedded images through ckeditor gets deleted after sometime
i have deployed my django app in heroku, postgresql as db and for storing images i haved used amazon S3 storage, the problem what i am facing is , for creating a blog post i have used ckeditor , so user can input images along with the content text for creating a post. after creating a post it looks like below when right clicked on post image and open link in new tab is selected, below is the url of S3 for the image uploaded after sometime images are deleted, only text content remains i have used S3 for thumbnail of the post which is direct image field , this doesn't get deleted , only problem is the post images which i embedded with content using ckeditor gets deleted after sometime of uploading . any extra information required , i will update it. thanks in advance ! -
Django Pattern: Celery + Async + Model Writing
I need to access multiple websites at once and save their data. I'm aware that Django isn't async and that models can't be accessed asynchronously. So what's an architecture I can use to achieve this? I'm using await asyncio.gather() to make the queries but I'm not sure how to get to writing this to the database synchronously. Send it to another task queue? Move it into an array and pop them out one at a time to write synchronously? -
Django ImageField GET api UnicodeDecodeError
I am getting a UnicodeDecodeError when I call the GET API for my model. The error is as follows: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte My models.py class RestaurantImage(CreateUpdateModel): image_type = models.CharField(verbose_name=_('Image Type'), choices=IMAGE_TYPES, max_length=255, default=RESTAURANT) restaurant = models.ForeignKey(verbose_name=_('Restaurant'), on_delete=models.PROTECT, to=Restaurant) image = models.ImageField(verbose_name=_('Select Image'), upload_to='media/') def __str__(self): return self.restaurant.name class Meta: verbose_name = 'Restaurant Image' verbose_name_plural = 'Restaurant Images' My serializers.py class RestaurantImageSerializer(serializers.ModelSerializer): restaurant = RestaurantSerializer(many=False, read_only=True) class Meta: from .models import RestaurantImage model = RestaurantImage fields = ('id', 'image_type', 'restaurant', 'image') My views.py class RestaurantImageListView(ListCreateAPIView): from rest_framework.permissions import AllowAny from rest_framework.filters import SearchFilter from .serializers import RestaurantImageSerializer from .models import RestaurantImage permission_classes = (AllowAny, ) serializer_class = RestaurantImageSerializer queryset = RestaurantImage.objects.all() filter_backends = (SearchFilter, ) search_fields = ('id', 'name') My post api works well, but the get api throws the error. I have also added the following MEDIA configuration to settings.py, MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' and to the main urls.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Please help me in solving this error, thank you. -
how to make the form to show using django anad ajax
i have a django website that include a form where it appear once the user click the submit button using ajax and using the crispy forms library until now i am able to do the function call back in the ajax and i get back the requested form where it display the result in the concole: "GET /books/create2/ HTTP/1.1" 200 3734 base.html {% load static %}<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Bookstore - Simple is Better Than Complex</title> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> {% include 'includes/header.html' %} <div class="container"> {% block content %} {% endblock %} </div> <script src="{% static 'js/jquery-3.1.1.min.js' %}"></script> <script src="{% static 'js/bootstrap.min.js' %}"></script> <script src="{% static 'js/plugins.js' %}"></script> {% block javascript %} {% endblock %} </body> </html> urls.py from django.contrib import admin from mysite.books import views from django.urls import path path('admin/', admin.site.urls), path('books/',views.book_list,name = 'book_list'), path('books/create2/',views.book_create2,name = 'book_create2'), views.py def book_create2(request): form = BookForm() context={ 'form':form } html_form = render_to_string('book_create2.html',context,request=request) return JsonResponse({'html_form':html_form}) book_list.html {% extends 'base.html' %} {% load static %} {% block javascript %} <!--<script src="{% static 'books/js/books.js' %}"></script>--> <script src="{% static 'js/plugins.js' %}"></script> {% … -
Asynchronous Python: Reading multiple urls from a synchronous library
I'm using python-twitter which isn't an asynchronous library and writing these to Django models. What I need to do for the sake of speed is read n batches of 100 user_ids at once. So: [[1234, 4352, 12542, ...], [2342, 124124, 235235, 1249, ...], ...] Each of these has to hit something like api.twitter.com/users/lookup.json. I've tried to use something like this, but it seems to run synchronously: await asyncio.gather(*[sync_users(user, api, batch) for batch in batches], return_exceptions=False) I've also tried wrapping the synchronous library calls, but that also seems to run synchronously. How can I send out all of the username lookup requests at once? loop = asyncio.get_event_loop() executor = ThreadPoolExecutor(max_workers=5) results = await loop.run_in_executor(executor, api.UsersLookup(user_id=batch, include_entities=True)) -
How do I append data to a many-to-many field using Ajax?
I'm trying to update user fields using ajax. I created an APIView for user model using rest-framework. User model includes a many-to-many field named "favorite_entries", with the code below I need to get all the field data beforehand in JS and append new data and call a put request, which seems wrong to me. views.py: class CurrentAuthorView(APIView): permission_classes = (permissions.IsAuthenticated, ) http_method_names = ['get', 'put'] def put(self, request): serializer = AuthorSerializer(request.user, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def get(self, request): serializer = AuthorSerializer(request.user) return Response(serializer.data) javascript: $("#favorite_entry-btn").on("click", function () { let entry_id = $(this).attr("data-entry-id"); $.ajax({ url: '/api/v1/author/', type: 'PUT', data: "favorite_entries=3", success: function (data) { alert('success'); }, error: function (err) { console.log(err); } }); }); I expect the entry with primary key "3" appended to the field, but it erases all the previous data. -
why swagger raises unclear error - Django
I have a django rest Backend app, and i use swagger to look and document my apis to the FE. This worked fine, but I made some changes and now I get this error: Internal Server Error: / Traceback (most recent call last): File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/rest_framework/views.py", line 497, in dispatch response = self.handle_exception(exc) File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/rest_framework/views.py", line 457, in handle_exception self.raise_uncaught_exception(exc) File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/rest_framework/views.py", line 468, in raise_uncaught_exception raise exc File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/rest_framework/views.py", line 494, in dispatch response = handler(request, *args, **kwargs) File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/rest_framework_swagger/views.py", line 32, in get schema = generator.get_schema(request=request) File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/rest_framework/schemas/coreapi.py", line 153, in get_schema links = self.get_links(None if public else request) File "/home/notsoshabby/.local/share/virtualenvs/panda_pitch-UBt5SNMA/lib/python3.7/site-packages/rest_framework/schemas/coreapi.py", line 140, in get_links link = view.schema.get_link(path, method, base_url=self.url) AttributeError: 'AutoSchema' object has no attribute 'get_link' HTTP GET / 500 [0.15, 127.0.0.1:44214] /home/notsoshabby/Desktop/panda_pitch/django_project/settings.py This error is not very clear as the AutoSchema is not a part of my code and the traceback is not showing me where in My … -
Convert whole Pycharm Project File (Contains GUI) into application
I was actually thinking if the whole Pycharm Project folder (which mainly contains GUI) can actually be converted into an application which in turn can be opened from any Unix server? This means to say that, whenever this application is launch, an automatic GUI will be created (let's say, on Chrome) if python manage.py runserver is commanded onto the same Unix server? Any comment and solution will be a great help, thank you. -
How to view advertises published by auser in his User serializer
I have user serializer in which i need to show in every user detail advertises which he published models.py: class Advertise(models.Model): title = models.CharField(max_length=120) publisher = models.ForeignKey(User, related_name='publisher',null=True, blank=True, on_delete=models.CASCADE) category = models.CharField(choices=CATEGORIES, max_length=120) description = models.TextField(max_length= 200, null=True, blank=True) image = models.ImageField(upload_to='project_static/Advertise/img', null=True, blank=False) price = models.DecimalField(decimal_places=2, max_digits=20) timestamp = models.DateTimeField(auto_now_add=True) approved = models.BooleanField(default=False) location = models.CharField(max_length=120 , null=True, blank=True) contact = models.CharField(max_length=120,null=True, blank=True) def __str__(self): """show ad name in admin page""" return self.title def get_absolute_url(self): return reverse("advertise:advertise-detail", kwargs={"pk":self.pk}) serilaizers.py: class AdSerializer(serializers.HyperlinkedModelSerializer): publisher = serializers.ReadOnlyField(source='publisher.username') url = serializers.CharField(source='get_absolute_url') class Meta: model = Advertise fields = ('url','id','title','publisher','category','description','price','timestamp','approved','location','contact') class UserSerializer(serializers.HyperlinkedModelSerializer): publisher = AdSerializer(source='publisher_set', many=True) class Meta: model = User fields = ['id', 'username','publisher'] error: Got AttributeError when attempting to get a value for field publisher on serializer UserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'publisher_set'. -
i am unable to use daterangepicker to my template for filter date-range. "Please help R" thanks in advance
Models.py class Expenses(models.Model): reg_date = models.DateField(auto_now_add=True) exp_id = models.AutoField(primary_key=True) # F description = models.CharField(max_length=200) expenses_value = models.IntegerField() def __str__(self): return str(self.exp_id) forms.py class Expensesform(forms.ModelForm): description = forms.CharField(widget=forms.Textarea(attrs={"rows":3, "cols":40,'class':'form-control','placeholder':'Enter Detail here...'}),required=True) expenses_value = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Enter Amount here...'}),required=True) class Meta: model = Expenses fields = ("description", "expenses_value") i used code base date which is working fine. but i am unable to user date-range picker input for costume date range result. mean user can use daterange picker to calculate expenses for such date range views.py def DailyExpReport(request): tday = datetime.date.today() datepicker1 = datetime.datetime.strptime('01072019', "%m%d%Y").date() total = 0 myexpenses = Expenses.objects.filter(reg_date__gte = start_Date, reg_date__lte=tday) today_entry = Expenses.objects.filter(reg_date__gte = start_Date, reg_date__lte=tday).aggregate( Sum('expenses_value')) return render (request, "blog/expenses_report.html",{'Expenses':myexpenses, 'total': today_entry}) Here is my template which is working fine for daily report or for specific coded date <!DOCTYPE html> {% extends "blog/base.html"%} {% block body_block %} <h1>Expenses Detail:</h1> <br> <div class="container"> <table class = "table"table table-striped table-bordered table-sm> <thead calss= "thead-dark"> <tr> <th>Date</th> <th>ID</th> <th>Description</th> <th>Expences Value</th> </tr> </thead> <tbody> {% for object in Expenses %} <tr> <td>{{object.reg_date }}</td> <td>{{object.exp_id }}</td> <td>{{object.description}}</td> <td>{{object.expenses_value}}</td> <td> <a href="/editexpenses/{{object.exp_id}}"><span calss = "glyphicon glyphicon-pencil">Edit</span> </a> <a href="/deleteexpenses/{{object.exp_id}}" onclick="return confirm('Are you sure you want to delete this item?');">Delete</a> </td> </tr> {% endfor%} </tbody> </table> … -
Where to get a detailed information about sessions in Django?
guys! I wanna to develop my own server via Django and now I want to understand how to work with sessions and cookies in Django. I'm interested in different examples, because I found a lot of theory, but I can't find good examples of implementation. So if someone has any books/tutorial/links where I can get acquainted with sessions in django, then I will be glad if you share the information. -
usercreationform doesn't show any field
I'm new to django and as my first project I'm trying to make a website which has a sign up page. In order to do that I'm trying to use UserCreationForm method. I don't get any errors and everything is just fine. The only problem is that it doesn't show any username or password field in the web page. I mean in doesn't show any field that the UserCreationForm is supposed to show. I searched a lot and I didn't find any related answer from django.shortcuts import render, redirect from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib import messages def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('blog-home') else: form = UserCreationForm() return render(request, 'users/register.html', {'from': form}) -
Import Python file which contains pySpark functions into Django app
I'm trying to import in views.py of my Django app, a python file "load_model.py" which contains my custom pyspark API but I got an error And I can't figure out how to solve it. I import the file "load-model.py" with a simple: import load_model as lm My load_model.py contains the following code (this is just part of the code): import findspark # findspark.init('/home/student/spark-2.1.1-bin-hadoop2.7') findspark.init('/Users/fabiomagarelli/spark-2.4.3-bin-hadoop2.7') from pyspark.sql import SparkSession from pyspark.ml.regression import RandomForestRegressionModel from pyspark.ml.linalg import Vectors from pyspark.ml.feature import VectorAssembler from pyspark.sql import Row from collections import OrderedDict spark = SparkSession.builder.appName('RForest_Regression').getOrCreate() sc = spark.sparkContext model = RandomForestRegressionModel.load('model/') def predict(df): predictions = model.transform(df) return int(predictions.select('prediction').collect()[0].prediction) # etc... ... ... when I lunch python manage.py run server on my command line, I get this error log: 19/07/20 07:22:06 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties Setting default log level to "WARN". To adjust logging level use sc.setLogLevel(newLevel). For SparkR, use setLogLevel(newLevel). Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/anaconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/anaconda3/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/anaconda3/lib/python3.7/site-packages/django/core/management/base.py", line 323, … -
My coupoun view doens't perform post request.It performs get which i don't want?
I made a coupon view which can basically see if the coupon exists and if it exists than reduce the amount of the total order but i get a strange csrf token in the url when i perform post Here's the coupon view def get_coupon(request, code): try: coupon = Coupoun.objects.filter(code=code) return coupon except ObjectDoesNotExist: messages.info(request, "This coupon does not exist") return redirect("item:cart") class Coupoun_view(generic.View): # First i have to get the order and the coupoun and then i have to detuct the amount the coupoun will use # If the order has a copoun then he can't use it again def post(self,*args,**kwargs): form = Coupoun_Form(self.request.POST or None) if form.is_valid(): code = form.cleaned_data.get("code") order = Order.objects.get( user=self.request.user, ordered=False) order.coupoun = get_coupon(self.request, code) print(order.coupoun) order.save() messages.success(self.request, "Successfully added coupon") return redirect("item:cart") Here's my cart view which will render out the form class Cart_View(generic.View,LoginRequiredMixin): def get(self,*args,**kwargs): order_item = OrderItem.objects.filter(user=self.request.user,ordered=False)[:3] # This is just for calling the subtotoal price of these 3 orders try: order_mini = Order.objects.get(user=self.request.user,ordered=False) qs1 = get_object_or_404(Order,user=self.request.user,ordered=False) # If the order is ordered and there is no order item which isn't ordered, # then there would be no order_item and hence there would be no order so i set them to … -
How to Implement 3-way Dependent/Chained Dropdown List with Django?
I am using django and postgresql. I'm dealing with a 3-way dependent drop-down list. After adding the country selection, the province area is automatically updated depending on the selected country. After selecting a province, the county field opens only when the page is refreshed. I would be glad if you help me in this regard. models.py from django.db import models class Country(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class City(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return self.name class District(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return self.name class Person(models.Model): name = models.CharField(max_length=100) birthdate = models.DateField(null=True, blank=True) country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) city = models.ForeignKey(City, on_delete=models.SET_NULL, null=True) district = models.ForeignKey(District, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name forms.py from django import forms from .models import Person, Country, City, District class PersonForm(forms.ModelForm): class Meta: model = Person fields = ('name', 'birthdate', 'country', 'city', 'district') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['city'].queryset = City.objects.none() if 'country' in self.data: try: country_id = int(self.data.get('country')) self.fields['city'].queryset = City.objects.filter(country_id=country_id).order_by('name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['city'].queryset = self.instance.country.city_set.order_by('name') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['district'].queryset = District.objects.none() … -
How to Create and change Dynamic shared and periodic_tasks tasks by api in Django
I'm using Celery to run periodic_tasks and schedule task. @shared_task def first(city): print(city) @celery_app.on_after_finalize.connect def first_periodic_tasks(sender, **kwargs): sender.add_periodic_task( crontab(minute=0, hour=15), job.s('test'), ) @celery_app.task def job(arg): print(arf) I want to create second_periodic_tasks dynamic using my api. AND I also want to change first_periodic_tasks run time using my api. How can i do this using Celery? -
I got this error when installing psycopg2 in Centos7
I'm using pip install psycopg2 but i got this error; Centos7 Collecting psycopg2 Using cached https://files.pythonhosted.org/packages/5c/1c/6997288da181277a0c2 9bc39a5f9143ff20b8c99f2a7d059cfb55163e165/psycopg2-2.8.3.tar.gz Building wheels for collected packages: psycopg2 Building wheel for psycopg2 (setup.py) ... error ERROR: Complete output from command /var/www/vhosts/sample.com/httpdocs/venv/ bin/python3 -u -c 'import setuptools, tokenize;__file__='"'"'/tmp/pip-install-bi jd4pos/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__ );code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(cod e, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-86gg6c3t --python-t ag cp36: ERROR: running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.6 creating build/lib.linux-x86_64-3.6/psycopg2 copying lib/pool.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/errors.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/tz.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/sql.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/_range.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/extensions.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/_lru_cache.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/compat.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/_json.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/__init__.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/errorcodes.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/_ipaddress.py -> build/lib.linux-x86_64-3.6/psycopg2 copying lib/extras.py -> build/lib.linux-x86_64-3.6/psycopg2 running build_ext building 'psycopg2._psycopg' extension creating build/temp.linux-x86_64-3.6 creating build/temp.linux-x86_64-3.6/psycopg gcc -pthread -Wno-unused-result -Wsign-compare -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fexceptions -fstack-protec tor-strong --param=ssp-buffer-size=4 -grecord-gcc-switches -m64 -mtune=generic - D_GNU_SOURCE -fPIC -fwrapv -fPIC -DPSYCOPG_VERSION=2.8.3 (dt dec pq3 ext) -DPG_V ERSION_NUM=90224 -I/usr/include/python3.6m -I. -I/usr/include -I/usr/include/pgs ql/server -c psycopg/psycopgmodule.c -o build/temp.linux-x86_64-3.6/psycopg/psyc opgmodule.o -Wdeclaration-after-statement In file included from psycopg/psycopgmodule.c:27:0: ./psycopg/psycopg.h:34:20: fatal error: Python.h: No such file or directory #include <Python.h> ^ compilation terminated. It appears you are missing some prerequisite to build the … -
Using custom schema in model's db_table
I have several schemas in postgresql. Now all of my django models are in public schema (i always have written db_table in models to manage table names). Now i need to migrate models from public schema (default) to new schema (named workadmin). How can i change postgres schema for my models? Change db_table to db_table = 'workadmin\".\"realty_land_plot' helped for many people, but those messages were for a long time ago. I have tried to use this way, but migrate command gave me the message: django.db.utils.ProgrammingError: ОШИБКА: ошибка синтаксиса (примерное положение: ".") LINE 1: ...TER TABLE "realty_land_plot" RENAME TO "workadmin"."realty_l... it means syntax error at "." symbol during alter table process. db_table = 'realty_land_plot'