Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
class Person(models.Model) why variable models can be used inside the class
I am a beginner of python and I have a question when I learn django, hope someone can help. (pls correct me if comments below is wrong) python document was read from django.db import models # this line is to import package of models class Person(models.Model): # this is to indicate Person inheritance of parent class Model, Model is the class name first_name = models.CharField(max_length=30) question is here: is "model" the package name, why it can be used this way models.CharField? can pls anyone explain? thanks a lot -
Searching Pages and custom models at the same time in Wagtail
I made a blunder - implemented some models in our application as plain Django models (but Indexable) instead of Page models. Now the client would like to see a unified search results page (so a faceted search is not adequate)... so I am completely stuck. We are using the PostgreSQL backend. The s.search() function requires a model or queryset; and you cannot combine PostgresSearchResults query sets. If I convert the 2 result sets to list and combine them I lose the relevancy of the results. Any ideas? -
Django migration cannot assign User instance to user field
Problem Recently I created a new migration for a SubscriptionAccount model which replaces an email field with a link to the User model. In this migration I also do a small data migration which fetches the users with the email and sets it to the SubscriptionAccount.user. However, for some reason the migration does not want to assign the user to the newly created user field. Complaining that it cannot assign a User instance ant that it expects a User instance. Which is weird, because that's exactly what I'm doing. Error The following error occurs: Traceback (most recent call last): File "./manage.py", line 13, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/usr/local/lib/python3.6/site-packages/django/db/migrations/migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/usr/local/lib/python3.6/site-packages/django/db/migrations/operations/special.py", line 193, in database_forwards self.code(from_state.apps, schema_editor) File "/project/hypernodedb/migrations/0069_link_subscription_account_to_user.py", … -
ValidationError: ["'' value has an invalid date format. It must be in YYYY-MM-DD format."] in django
when I initiate the request for the date field name as dob with the respective value of dob is "dob":"1996-10-25" Model.py class Register_model(models.Model): UserId = models.CharField(max_length=255,default='',blank=True,null=True) ISpinId = models.CharField(max_length=255,primary_key=True, unique=True,default='', blank=True,null = False) email = models.CharField(max_length=250, unique=True) first_name = models.CharField(max_length=250, default="",null = False) last_name = models.CharField(max_length=250, default="",null = False) dob = models.DateField(auto_now_add=False, auto_now=False) password = models.CharField(max_length=255,blank=False,null = False) gender = models.CharField(max_length=50,default="",null = False) nationality = models.CharField(max_length=100,default="",null = False) views.py @permission_classes((AllowAny,)) class User_RegisterAPIViews(APIView): # Serializer Initilization print("dasf") serializers = serializers.Register_Serializer # Post method Declarations def post(self, request): request.POST._mutable = True print(request.data) request.data['ISpinId'] = etc.random_number_generate(request.data['first_name'], request.data['last_name']) password = request.data['password'] print(request.data['dob']) playersCategory, age = etc.age_convert(request.data['dob'], request.data['gender']) request.data['players_category'] = playersCategory request.data['age'] = age form_data = serializers.Register_Serializer(data=request.data) if form_data.is_valid(): print("formdata",form_data) form_data.save() # File Save Error : Traceback (most recent call last): File "/home/shawn-codoid/Music/virtual/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/shawn-codoid/Music/virtual/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/shawn-codoid/Music/virtual/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/shawn-codoid/Music/virtual/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/shawn-codoid/Music/virtual/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/shawn-codoid/Music/virtual/lib/python3.6/site-packages/rest_framework/views.py", line 497, in dispatch response = self.handle_exception(exc) File "/home/shawn-codoid/Music/virtual/lib/python3.6/site-packages/rest_framework/views.py", line 457, in handle_exception self.raise_uncaught_exception(exc) File "/home/shawn-codoid/Music/virtual/lib/python3.6/site-packages/rest_framework/views.py", line 468, in raise_uncaught_exception raise exc File … -
Running a scheduled zappa function manually
I want to test the event in zappa_settings.json locally I have set up the environment and I have the server running a Django site on my local machine, I am also able to deploy the Django site to AWS via Zappa. Before pushing it to the cloud I would like to test the event which is used to deploy a cronjob to the cloud with Lambda functions. I keep getting errors on the imports. Here is my Event in zappa_settings.json "events": [{ "function": "main.kpi_report.auto_scraper", "expression": "cron(20 12 * * ? *)" // "expression": "rate(10 minutes)" }], Here are the imports in my kpi_report.py file from .mws_settings import mws_settings from .util import get_country_by_marketplace_name, date_amz_to_normal, process_currency from .dynamodb import KPI Python3 manage.py runserver System check identified no issues (0 silenced). You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions. Run 'python manage.py migrate' to apply them. October 03, 2019 - 12:23:46 Django version 2.0.7, using settings 'com.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. Then finally when I run the auto_scrapper manually on my local machine: t$ python main/kpi_report.py auto_scrapper Traceback (most recent call last): File … -
How can I pass content between apps in django?
My current project is composed to two apps. One is a kind of catalog of products. The other is a blog. The product catalog app is pointed to the main or index page. I want to add a side bar on there where the new blog posts from the other app will appear. This is what I have so far. Can someone tell me what I am doing wrong? Views from blog.models import Post def index(request): Transmitters = reversed(Album.objects.all()) receiver = reversed(Receiver.objects.all()) posts = (Post.objects.all()) context = {'Transmitters': Transmitters , 'Receivers': receiver, 'Post': posts} return render(request, 'music/index.html', context) URLs urlpatterns = [ # /index/ url(r'^$', views.index, name='index'), ] HTML <div class="container container-fluid"> {% for post in posts %} <article class='media content-section'> <img class='rounded-circle article-img' src='{{ post.author.profiles.image.url }}'> <div class='media-body'> <div class='article-metadata'> <br>Published by <b>{{ post.author |capfirst}}</b> | <small class='text-muted'>{{ post.created }}</small> </div> <h2><a class='article-title' href="{{ post.get_absolute_url }}"><b>{{ post.title }}</b></a></h2> <p class="lead"> {{post.body|safe|truncatewords:80}} </p> </div> </article> {% endfor %} </div> -
How to translate whole html page in another language in Django?
Currently I am developing website using Django framework & I have to translate my web page into another language (French) & all other pages are in English language. <html lang="fr"> I have set like above but code not working & getting page in English language only. -
Implementing LEFT JOIN explicitly in Django
I have been thru endless posts on Django and the LEFT JOIN problem and but have not found anyone that has a solution in the 2.2 version of Django. Whilst in years past it seems there were ways to get around this problem, the Django team seem to have shut down every mechanism people have employed to achieve the most simple but necessary query - the LEFT JOIN. Here is a simle example of what I am trying to do (it is a simple example to reflect a real world scenario so please do not offer ways to redesign the models... all I want is the age old LEFT JOIN in SQL .... that simple): from django.db import models from uuid import uuid4 class People(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid4) name = models.CharField(max_length=255) class Book(models.Model): id = models.UUIDField(primary_key=True, editable=False, default=uuid4) name = models.CharField(max_length=255) author = models.ForeignKey(People) publisher = models.ForeignKey(People, on_delete=models.PROTECT, null=True) How would I achive an output showing all books and the publisher if there is a publisher (otherwise just blank) Books.objects.filter(Q(publisher__isnull=True | Q(publisher__isnull=False) ... produces an INNER JOIN which will obviously only show books that have a publisher assigned. The query I am looking for would be of the … -
how to add new column to model which is referenced to other model by foreign key in django
I have a model named Shape: class Shape(models.Model): name = models.CharField(max_length=40, unique=True) and another model named Tank which has Shape model as foreignkey: def get_default(model): value, is_created = model.objects.get_or_create(name=0) return value.id class Tank(models.Model): name = models.CharField(max_length=50) shape = models.ForeignKey(Shape, on_delete=models.SET_DEFAULT, default=get_default(Shape), related_name="tanks") when i try to add a new column(with null=True) in Shape model, at python manage.py makemigrations django raises a error: django.db.utils.OperationalError: no such column: tank_shape.Column name -
Django AJAX library
I am trying to implement django_ajax library(https://github.com/yceruto/django-ajax) in my project. So, this example works fine: #views.py from django.http import HttpResponse from django.shortcuts import render from django.views.generic.edit import FormView from django.views.generic.base import TemplateView from django.urls import reverse_lazy from django_ajax.mixin import AJAXMixin from .forms import NameForm class NameView(FormView): template_name = 'postajax.html' form_class = NameForm success_url = reverse_lazy('myapp:success') def form_valid(self, form): return super().form_valid(form) class SuccessView(AJAXMixin, TemplateView): template_name = 'success.html' def __init__(self, **kwargs): super().__init__(**kwargs) self.ajax_mandatory = False #postajax.html <!DOCTYPE html> <html id="successhtml"> <head> <title>Page Title</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> </head> <body> <form action="" method="post" id="frm"> {% csrf_token %} {{ form.as_p}} <input type="submit" value="Submit"> </form> <script> var frm = $('#frm'); frm.unbind('submit').submit(function () { $.ajax({ type: frm.attr('method'), url: frm.attr('action'), data: frm.serialize(), success: function (data) { console.log(data) $('#successhtml').html(data.content) }, error: function(data) { alert("Something went wrong") } }); return false; }); </script> </body> </html> the response is: { content: "<!DOCTYPE html>\n<html>\n<head>\n<title>Page Title</title>\n</head>\n<body>\n\n\n<p>Success</p>\n\n</body>\n</html>", status: 200, statusText: "OK" } everything is oke. My real project structure (where i want to implement AJAXMixin) looks something like this: #views.py class MyView(AJAXMixin, FormView): def get(self, request, *args, **kwargs): response = super().get(request, *args, **kwargs) . . retrurn response def form_valid(self, form): . . . . return super().form_valid(form) def get_success_url(self): return reverse(...) I skipped the non-relevant lines. … -
Save GEOJSON file to database
In my templates form, i have a script where the loggedin user can draw a polygon and export it as a geojson. I would like to save this drawn polygon to the database. I have created a model : plot = models.PolygonField() But i don't know how to pass this export to the plot -
Sidebar / Navbar in Django
How can I create a Django project with a fixed sidebar that rarely change? Currently on every page I visit, whole page is reloaded which means sidebar too. It is kinda irritating. Thanks in advance! -
Django Time Series Data - Handling multiple CSVs
I am working on a homework related to Django framework. The problem is the following: I was provided with a .csv file containing patients' record: 1- Name 2- Age 3- Weight Each patient also has a separate .csv file, containing hundreds of data points for the patient blood pressure (timestamp every 20 minutes). So I assume I need to add 2 more variables: 4- Datetime variable that captures the time 5- Blood Pressure (BOTH 4 AND 5 ARE TIME SERIES AS DESCRIBED ABOVE) As a first step I need to load the user data through django. The Problem is: 1) For the first 3 variables, I would create a model form defining each variable with its corresponding type (say charfield()). For the blood pressure and the Datetime, what is the most efficient way to proceed? (PS: I AM USING DJANGO 1.11) 2) The files should be loaded using a django Management Command File(.py file). What is the most efficient way to load all the .csv files into the django framework? (I have 1 file containing all the patients with their age and name, and each patient has a separate .csv file with the blood pressure records). -
Django deployed website takes too long to load
I've been trying to run a Django CRM project that I've made and deployed on both AWS and Azure VMs. I have deployed both the PostgreSQL database and the project itself into a single VM with okay-ish specs. The runtime for a certain page with close to 600 rows (in a Datatable) is around 26 seconds locally. After deploying, the runtimes have been around 40 seconds on the live version, but onnce I access the website from various different computers at the same time, it seems to slow down immensely and crashes sometimes. The stack I've used in this project is something I've used in my other projects too, I would really like to know if there is a way to make this any faster or if it's just the end of it. The stack includes: - Django Python - PostgreSQL - HTML/CSS, Ajax, JQuery I've increased the number of cores and RAM in the virtual machines, but there's no change in load time. I've optimized my code, used datatables, etc but no signs of it being any faster. -
How to have Django Rest Framework serializer return same format as Django core serializer
Using Django Rest Framework I'm trying to return my queryset with the data nested under the model's primary key. This is the default format if using an http request with Django's core serializer and JsonResponse. I'm trying to get my DRF ModelSerializer to return in the same format. I've looked through the docs but don't see anything about altering the output format. Django's core serializer returns the queryset nested below a primary key. @csrf_exempt @api_view(['POST']) def search_foods_http(request): post_data = request.data['params']# 'Params' from axios request print(post_data) search_qry = post_data['search_qry'].lower() food_type_grp = post_data['food_type_grp'] search_results = Foods.objects.filter(food_description__contains=search_qry,food_type_grp__in=food_type_grp) return JsonResponse(core.serializers.serialize('json',search_results), safe=False) results: "[{\"model\": \"food.foods\", \"pk\": 329246, \"fields\": {\"food_description\": \"builder's bar - crunchy peanut butter\", ... Whereas a Django Rest Framework ModelSerializer response @api_view(['POST']) def search_foods(request): post_data = request.data['params'] # 'Params' from axios request search_qry = post_data['search_qry'].lower() food_type_grp = post_data['food_type_grp'] search_results = Foods.objects.filter(food_description__contains=search_qry,food_type_grp__in=food_type_grp) serializer = FoodModelSerializer(search_results, many=True) return Response(serializer.data) returns data without the primary key. [ { "food_key": 329246, "food_description": "builder's bar - crunchy peanut butter", ... Does anyone know if there's specify to do this? I don't want to iterate through the queryset in View. -
How to solve blocked access to XMLHttpRequest at 'URL' by CORS policy?
I suddenly got the following error when working with AJAX in my virtualenv to make API calls AND already studied a bunch of SO threads about similar issues: Access to XMLHttpRequest at 'http://www.api-football.com/demo/api/v2/teams/team/77/' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I run the latest Python + Django and Google Chrome Versions. What I've already tried: cleared my browsers cache installed cors app, included it in Apps, included middleware accordingly set CORS_ORIGIN_ALLOW_ALL = True and CORS_ALLOW_CREDENTIALS = True tried a different API, same error installed and activated the google chrome CORS extension, same error changed DataType to jsonp, error gone BUT then i end up with the following error: jquery.min.js:2 Cross-Origin Read Blocking (CORB) blocked cross-origin response https://api.footystats.org/league-teams?key=example&include=stats&league_id=1625&callback=jQuery34101697774297755965_1570102531537&_=1570102531538 with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details. My settings.py ALLOWED_HOSTS = ['127.0.0.1'] SILENCED_SYSTEM_CHECKS = [ 'admin.E408', 'admin.E409', 'admin.E410', ] DEBUG = 'TRUE' #Rooting ROOT_URLCONF = 'dasocc_site.urls' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") #Applications CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ] INSTALLED_APPS = [ 'corsheaders', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', … -
id the field is required - error in Django formset
I am using Django 2.2. My models are class Group(models.Model): group_name = models.CharField(max_length=100) def __str__(self): return self.group_name class Category(models.Model): category_name = models.CharField(max_length=50) def __str__(self): return self.category_name class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) board = models.CharField(choices=board_options,max_length=1,null=True) group = models.ForeignKey(Group,on_delete=models.CASCADE,null=True) class Subject(models.Model): subject_name = models.CharField(max_length=50) subject_category = models.ForeignKey(Category, on_delete=models.CASCADE) subject_photo = models.ImageField(null=True,blank=True) def __str__(self): return self.subject_name class Subject_Assignment(models.Model): board = models.CharField(choices=board_options,max_length=1,null=True) group = models.ForeignKey(Group,on_delete=models.CASCADE,null=True) Subject = models.ForeignKey(Subject, on_delete=models.CASCADE) class Mark_Survey(models.Model): survey_name = models.CharField(max_length=50) opens_at = models.DateField() ends_at = models.DateField() class Survey_Mark(models.Model): mark_survey = models.ForeignKey(Mark_Survey,on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) Subject = models.ForeignKey(Subject, on_delete=models.CASCADE) marks = models.IntegerField() Here am creating a formset for Survey_Mark and my form should get marks of all Subject. By using Subject_Assignment i can get all the subjects of the particular user.The following view works for the get method but throws error in post method. def postsurvey(request,pk): #post = get_object_or_404(Mark_Survey, pk=pk) SurveyFormSet = modelformset_factory(Survey_Mark, fields=('marks','Subject'),extra=0) if request.method == "POST": formset = SurveyFormSet(request.POST,request.FILES) print(formset.data) print(formset.errors) if formset.is_valid(): post = formset.save(commit=False) post.mark_survey=pk post.user=request.user post.save() html = "<html><body>Success</body></html>" % now return HttpResponse(html) else: print("failure") html = "<html><body>failure </body></html>" return HttpResponse(html) else: user=request.user profile = get_object_or_404(Profile,user_id=user.id) formset = SurveyFormSet(queryset=Subject_Assignment.objects.filter(Q(board=profile.board) & Q(group=profile.group))) return render(request, 'subject_assignment_detail.html', {'formset': formset}) Am getting id the field is required error. … -
Do id primary key have to be explicitly defined in Django models generated from inspectdb against an existing database?
I have an existing MySQL database with several tables already populated with data. I created and configured a Django project with an application. Communication between Django and the database works as expected. I have generated a 'models.py' using 'inspectdb' command to create all my application models: python manage.py inspectdb > myapp/models.py My issue is that none of my models shows any 'id' field in 'models.py'. All existing MySQL tables having an 'id' column as primary key (auto increment being enabled for those) it seems weird. I wonder if I need to explicitly add 'id' primary keys fields in all model classes created with inspectdb or if it is not needed (it would be implicit in that case). Why 'id' primary key is missing from Django models definitions and should I add this field to the models classes? -
mysql query filter LIKE not working properly
i have a column campaign_name. and user might type and look for incase sensitive string keyword. for example they entered "adopt a patient". but inside my table the campaign_name: i have "adopt-a-patient +---------------- |campaign_name | +---------------- |adopt-a-patient| ----------------- select * from campaign where campaign_name LIKE '%ADOPT A PATIENT%'; return ZERO result my campaign_name collation already set to utf8_general_ci.but if users entered exactly the word "adopt-a-patient" the result returned as expected. any help would be much appreciated. anyway im implementing it on django app. im just debug it inside HeidiSQL. -
Soft-coding values to a yaml file for loaddata option
I have the following model: class Plan(TimeStampedModel): name = models.CharField(_("Plan name"), max_length=50, null=False, blank=False, unique=True) The TimeStampedModel it inherits from has created and changed dates: class TimeStampedModel(models.Model): """Reusable template to add created/last updated timestamps to a model""" created_at = models.DateTimeField(_("Created"), auto_now_add=True) changed_at = models.DateTimeField(_("Last changed"), auto_now=True) class Meta: abstract = True Now I run a loaddate from yaml files looking like this: - model: plans.Plan pk: 1 fields: name: Basic plan This gives me an error because the load complains that I haven't defined the timestamp data. What I would like to do, rather than just setting a default timestamp (which I can if it becomes necessary), is just pass the current tiemstamp for the date/time I am running loaddata, which will then get applied to all the yaml files. Running python manage.py testserver demo_data/fixtures/plans.yaml bypasses the DB constraints, and the auto_add options as far as I can see, so the way these fields would normally be set isn't applied. Is there a way of doing this? I can't find anything, not even a similar question, in my searches. -
Django Haystack Scoring seems incorrect
The scoring that im seeing in my search results seems incorrect to me, im not sure if I need to do anything to improve the accuracy of score. in the below example using 'ches', Chester should score high but its scored less than Chelmsford for some reason? query = 'ches' sqs = SearchQuerySet().filter(content=AutoQuery(query)) paginator = Paginator(sqs, 10) page = request.GET.get('page') try: results = paginator.page(page) except PageNotAnInteger: results = paginator.page(1) except EmptyPage: results = paginator.page(paginator.num_pages) >>> for i in results.object_list: ... i.score, i.text ... (7.616099, 'STR-CHEL-RTR-02\n') (7.5457063, 'STR-CHEL-NVR\n') (7.290444, 'STR-CHES-NVR\n') (6.81494, 'Chester\n65001\nCH1 ABC') (6.6442084, 'STR-CHEL-RTR-01\n') (6.493678, 'STR-CHES-RTR-02\n') (6.357569, 'STR-CHES-SW-03\n') (6.357569, 'STR-CHES-RTR-01\n') (5.7965107, 'Chelmsford\n65002\nCM1 ABC') indexes if relevant class DeviceIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True) def get_model(self): return Device def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().objects.all().select_related('site') class SiteIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.EdgeNgramField(document=True, use_template=True) def get_model(self): return Site def index_queryset(self, using=None): """Used when the entire index for model is updated.""" return self.get_model().objects.all() and search texts device_text.txt {{ object.hostname }} site_text.txt {{ object.location }} {{ object.bgp_as}} {{ object.postcode }} -
How can I restrict access to a view to only super users in Django
On a site I am developing in Django, I want to restrict access to views so only superusers can access them. I could use @login_required or the LoginRequiredMixin, however I already have a login system for the average person, so that would let any logged in user access the view. I've tried something that I thought would work SuperUserRequired as a mixin, however this obviously didn't work. This has to be able to work in a CBV, as that's what I am using for this view. Here is the relevant view I want to apply this restriction to. class CreatePostView(LoginRequiredMixin,CreateView): redirect_field_name = 'posts/post_detail.html' form_class = PostForm model = Post def form_valid(self,form): form.instance.author = self.request.user return super().form_valid(form) Thanks for any help you can give :) -
How to pass a variable from a script in a template to a model
I my template, I compute the variable area from a polygon drawn in a map. I would like to pass this value to the database when the user will complete a form. So once the user is on the page, i would like him to complete the form and to draw a polygon on a map. When this polygon is draw I would like the field area of the from(and the table fertisatdb) to update. How can I do this ? script in template.html mapboxgl.accessToken = var map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/satellite-streets-v10', center: [-7.60,33.57], zoom: 5, bearing: 0 }); var draw = new MapboxDraw({ displayControlsDefault: true }); map.addControl(draw); map.on('draw.create', updateArea); map.on('draw.delete', updateArea); map.on('draw.update', updateArea); function updateArea(e) { var data = draw.getAll(); var answer = document.getElementById('calculated-area'); if (data.features.length > 0) { var area = turf.area(data); // restrict to area to 2 decimal points var rounded_area = Math.round(area*100)/100; answer.innerHTML = '<p><strong>' + rounded_area + '</strong></p><p>square meters</p>'; var convertedData = 'text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(data)); document.getElementById('export').setAttribute('href', 'data:' + convertedData); document.getElementById('export').setAttribute('download','data.geojson'); } else { answer.innerHTML = ''; if (e.type !== 'draw.delete') alert("Use the draw tools to draw a polygon!"); } } models.py from django.db import models as db_models from django.contrib.auth.models import User from … -
Django Channels send group message from Celery task. Asyncio event loop stopping before all async tasks finished
I'm currently stuck on a particularly tricky problem, I'll try my best to explain it. I have a Django project and it's main purpose is to execute queued tasks from a DB rapidly. I use Celery and Celerybeat to achieve this with Django channels to update my templates with the responses in real time. The Celery worker is a gevent worker pool with a decent number of threads. My Task(Simplified version): @shared_task def exec_task(action_id): # execute the action action = Action.objects.get(pk=action_id) response = post_request(action) # update action status if response.status_code == 200: action.status = 'completed' else: action.status = 'failed' # save the action to the DB action.save() channel_layer = get_channel_layer() status_data = {'id': action.id, 'status': action.status} status_data = json.dumps(status_data) try: async_to_sync(channel_layer.group_send)('channel_group', {'type': 'propergate_status', 'data': status_data}) except: event_loop = asyncio.get_running_loop() future = asyncio.run_coroutine_threadsafe(channel_layer.group_send('channel_group', {'type': 'propergate_status', 'data': status_data}), event_loop) result = future.result() My Error: [2019-10-03 18:47:59,990: WARNING/MainProcess] actions queued: 25 [2019-10-03 18:48:02,206: WARNING/MainProcess] c:\users\jack\documents\github\mcr-admin\venv\lib\site-packages\gevent_socket3.py:123: RuntimeWarning: coroutine 'AsyncToSync.main_wrap' was never awaited self._read_event = io_class(fileno, 1) RuntimeWarning: Enable tracemalloc to get the object allocation traceback [2019-10-03 18:48:02,212: WARNING/MainProcess] c:\users\jack\documents\github\mcr-admin\venv\lib\site-packages\gevent_socket3.py:123: RuntimeWarning: coroutine 'BaseEventLoop.shutdown_asyncgens' was never awaited self._read_event = io_class(fileno, 1) RuntimeWarning: Originally after I saved the action to the DB I just called: async_to_sync(channel_layer.group_send)('channel_group', {'type': … -
What is the best way to deliver django project as a full installation file (setup.exe) to be user-friendly and not revealing your whole scripts?
I have a django project which is working fine. However, this question can be related to any django project. Django works in a way that after running python manage.py runserver the project is accessible at localhost:8000. But when you deliver the project to the customer you cannot expect them to open command windows every time, then run python manage.py runserver, then open a browser, then type localhost:8000 and etc. I have heard docker might be a solution to this. But docker will need the scripts available in the local machine. I am talking about making a full installation file like when you buy a video game and the scripts are not accessible easily (seems there are binary files). The real question is how can we protect our code and scripts and be sure they cannot be accessed easily after we have installed them in a customer's computer?