Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
If you see valid patterns in the file then the issue is pro bably caused by a circular import
I tried to import pyrebase in my views.py, but I've got an error arisen: Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\urls\resolvers.py", line 581, in url_patterns iter(patterns) TypeError: 'module' object is not iterable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\USER\AppData\Local\Programs\Python\Python36\lib\threading.py", line 916, in _bootstrap_inner self.run() File "C:\Users\USER\AppData\Local\Programs\Python\Python36\lib\threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\core\management\base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\core\management\base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\urls\resolvers.py", line 398, in check for pattern in self.url_patterns: File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\utils\functional.py", line 80, in get res = instance.dict[self.name] = self.func(instance) File "C:\Users\USER\Documents\python projects\yerekshe\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'yerekshe.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is pro bably caused by a circular import. here is my views.py: from django.shortcuts import … -
What is the meaning of detail argument in Django ViewSet?
I create a custom action method in Django ViewSet and I see detail argument. If I set detail=True I can't call this method from URL but if I set detail=False, I can call this method. May I know what is the meaning of detail argument? Here is my method=> @action(methods=['get'], detail=True) def byhello(self, request): return Response({"From Hello":"Got it"}) -
why does super function exactly use in my code?
My problem is about why exactly was super(CommentManager, self) used in code below. couldn't that instance object in filter_by_instance just be used instead? class CommentManager(Models.Manager): def filter_by_instance(self, instance): content_type = ContentType.objects.get_for_model(instance.__class__) obj_id = instance.id qs = super(CommentManager, self).filter(content_type=content_type, object_id=obj_id).filter(parent=None) return qs Couldn't it be something like this: class CommentManager(Models.Manager): def filter_by_instance(self, instance): content_type = ContentType.objects.get_for_model(instance.__class__) obj_id = instance.id qs = instance.filter(content_type=content_type, object_id=obj_id).filter(parent=None) return qs -
Use some Pandas Functions into my Django App
Hi guys I have a problem: I've made my first Django App extensively using pandas in my views.py to load csvs, make some data prep and loading my pickle ML model. The problem is that all this was working fine until I tested on the deployed app (using nginx and uwsgi) where I got an error No Module named pandas which, researching seems to be a very common issue due to the fact that Django doesn't allow importing pandas directly. I saw some Django-pandas frameworks but their documentation is quite cryptic to me. Can you explain me in a simple way How can I execute those functions in pandas using Django (even with the help of a Django-pandas framework): pandas.read_csv() DataFrame.loc[...] DataFrame.sort_values() Series.unique() Series.size Series.iloc[0] DataFrame.from_dict(...) # would pickle function be affected? model = pickle.load(open(...)) model.predict() To make a better example: import pandas as pd df = pd.read_csv('...') df = df.loc[df['...'] == '...'] serie = df['...'].sort_values() serie = pd.Series(serie.unique()) serie.size value1 = int(serie.iloc[0]) df = pd.DataFrame.from_dict(dictionary) model = pickle.load(open(...)) # I don't know if pickle would give problems as well as pandas prediction = model.predict(df) -
Django template check value with URL parameter
I'm trying to create a select in html to list all month and the default value of the select should be equal to the month parameter from the URL My URL : /list-working-session/?month=7&year=2019 month and year are the parameter in My HTML: <select name="month" class="form-control" id="month" required> {% for i in months %} {% if i == request.GET.month %} <option value="{{ i }}" selected="selected">{{ i }}</option> {% else %} <option value="{{ i }}">{{ i }}</option> {% endif %} {% endfor %} </select> months is the context from the view with range(1,13) and i managed to list from 1 to 12 in select option but i can't get the IF condition to work so the default select value equal to the month in the URL. Any help would be appreciate -
Can I call location.reload() from HttpResponseRedirect?
Is it possible to call location.reload() when using HttpResponseRedirect using Django? I have a function that changes the state of an item when a button is clicked. Often the user scrolls down to click this button. The button is hooked up to the view change_state: def change_state(request, item_title, new_state): modify_state(item_title, new_state) return HttpResponseRedirect(reverse('slug-of-prev-page')) When I redirect to slug-of-prev-page the entire page will reload, snapping the page to the top. I know using something that manipulates the DOM, like React.js, would be better for this type of thing. But I'm looking for a quick solution. Or is my best bet to hook up a call to change_state, POST the data, and then call location.reload()? -
How to create another superuser in django?
I have a user created in django and I want to create another user but when I try to create it gives me error. djongo.sql2mongo.SQLDecodeError: FAILED SQL: INSERT INTO "auth_user" ("password", "last_login", "is_superuser", "username", "first_name", "last_name", "email", "is_staff", "is_active", "date_joined") VALUES (%(0)s, %(1)s, %(2)s, %(3)s, %(4)s, %(5)s, %(6)s, %(7)s, %(8)s, %(9)s) Params: ['pbkdf2_sha256$150000$MqcpwdeHoQyA$yXEd56NQb5QfWNwwjZOIS0OJmzVpUizpRsTWoHNPgEw=', None, True, 'bilalkhan', '', '', '', True, True, datetime.datetime(2019, 7, 30, 8, 30, 16, 156047)] Pymongo error: {'writeErrors': [{'index': 0, 'code': 11000, 'errmsg': 'E11000 duplicate key error collection: firstapp_db.auth_user index: auth_user_email_1c89df09_uniq dup key: { : "" }', 'op': {'id': 49, 'password': 'pbkdf2_sha256$150000$MqcpwdeHoQyA$yXEd56NQb5QfWNwwjZOIS0OJmzVpUizpRsTWoHNPgEw=', 'last_login': None, 'is_superuser': True, 'username': 'bilalkhan', 'first_name': '', 'last_name': '', 'email': '', 'is_staff': True, 'is_active': True, 'date_joined': datetime.datetime(2019, 7, 30, 8, 30, 16, 156047), '_id': ObjectId('5d4000187b6675a2aa5457b5')}}], 'writeConcernErrors': [], 'nInserted': 0, 'nUpserted': 0, 'nMatched': 0, 'nModified': 0, 'nRemoved': 0, 'upserted': []} Version: 1.2.33 -
Why validate_<field> triggered 3 times? Django Rest Framework
I have following cutsom base Serializer: class CustombBaseSerializer(Serializer): def get_object(self, model, **kwargs): try: return model.objects.get(**kwargs) except model.DoesNotExist: raise ValidationError( f"{model._meta.verbose_name.title()} Does Not Exist." ) and following serializer inherited from CutsomBaseSerializer (above): class TextAnswerSerializer(CustombBaseSerializer): sheet_code = CharField( max_length=11, ) def validate_sheet_code(self, value): return self.get_object(SheetCode, pk=value) def validate(self, attrs): if attrs.get('sheet_code').user_id != attrs.get('user_id'): raise ValidationError("It's not yours!") if attrs.get('sheet_code').kind == 'infinity': # some stuff elif attrs.get('sheet_code').kind == 'feedback': # some more stuff else: # some other stuff return attrs when I send data to this serializer, it raises an exception: myapp.models.SheetCode.MultipleObjectsReturned: get() returned more than one SheetCode -- it returned 3! I find that, the validate_sheet_code triggered 3 times. what's the problem? and how to fix it? -
How to display the custom message with django axes?
I implemented the django-axes to lockout the user if the user tried too many attempts.But the one thing is if the user account locked it displays the messages in the new page with Account locked: too many login attempts. Please try again later which is fine but however i want to modify this message like try again in 1 minutes or something like this.And also i want to display this message along with my login form like the django contrib messages does. settings.py import datetime AXES_COOLOFF_TIME = datetime.timedelta(minutes=2) AXES_FAILURE_LIMIT = 5 views.py if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] remember_me = form.cleaned_data['remember_me'] user = authenticate(request, username=username, password=password) if user and user.is_active: login(request, user) if not remember_me: request.session.set_expiry(0) redirect_url = request.GET.get('next', 'home') return redirect(redirect_url) elif user and not user.is_active: messages.info(request, 'Your account is not active now.') else: messages.error(request, 'Invalid Username and Password') -
If a client login from a particular centre then that client could see only his centre in foreign key
I have registered a user from a particular centre and after that he logged in .Now I want that he could only see his centre name as foreign key when he fills the cabin form .I have centre model where all the centre details will be there which is foreign key to userprofile model and cabin model has foreign from userprofile .so now i want when user loggin from a particular centre he see his centre name only in dropdown menu of foreign key .since I am new to django kindly help me .Thank you in advance. models.py class Centre(models.Model): name= models.CharField(max_length=50, blank=False, unique=True) address = models.CharField(max_length =250) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'. Up to 10 digits allowed.") contact = models.CharField(max_length=100, blank=False) phone = models.CharField(validators=[phone_regex], max_length=10, blank=True) # validators should be a list slug = models.SlugField(unique=False,blank=True) def save(self, *args, **kwargs): self.slug = slugify(self.name) super(Centre, self).save(*args, **kwargs) def __str__(self): return self.name def get_absolute_url(self): return reverse("index") Roles = ( ('sales', 'SALES'), ('operations', 'OPERATIONS'), ('cashier', 'CASHIER'), ('frontdesk', 'FRONTDESK'), ('client', 'CLIENT'), ) class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE, default=None, null=True) role = models.CharField(max_length=50, choices=Roles) verified =models.BooleanField(default = False,blank=True) photo = models.ImageField(upload_to='users/', blank=True, default='default/testimonial2.jpg') slug = models.SlugField(unique=False, blank=True) centres … -
How to use registration(signup/login) modal(bootstrap template) with django views?
I am new to programming. I found nice bootstrap modal for registration, so i put it to my html code and it looks nice but nothing can be pressed or post. Before i was using django and UserCreationForm without modals. So help me to concatenate these two things: so this is my bootstrap modal that i found <!-- Modal --> <div class="modal fade" id="elegantModalForm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <!--Content--> <div class="modal-content form-elegant"> <!--Header--> <div class="modal-header text-center"> <h3 class="modal-title w-100 dark-grey-text font-weight-bold my-3" id="myModalLabel"><strong>Войти</strong></h3> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <!--Body--> <form type="post" action="{% url 'common:login' %}"> <div class="modal-body mx-4"> <!--Body--> <div class="md-form mb-5"> <input type="email" name="useremail" id="Form-email1" class="form-control validate"> <label data-error="wrong" data-success="right" for="Form-email1">Ваша почта</label> </div> <div class="md-form pb-3"> <input type="password" id="Form-pass1" class="form-control validate"> <label data-error="wrong" data-success="right" for="Form-pass1">Пароль</label> <p class="font-small blue-text d-flex justify-content-end">Забыли <a href="#" class="blue-text ml-1"> пароль?</a></p> </div> <div class="text-center mb-3"> <button type="button" class="btn blue-gradient btn-block btn-rounded">ок</button> </div> <p class="font-small dark-grey-text text-right d-flex justify-content-center mb-3 pt-2"> или войти с помощью:</p> <div class="row my-3 d-flex justify-content-center"> <!--Facebook--> <button type="button" class="btn btn-white btn-rounded mr-md-3 z-depth-1a"><i class="fab fa-facebook-f text-center"></i></button> <!--Twitter--> <button type="button" class="btn btn-white btn-rounded mr-md-3 z-depth-1a"><i class="fab fa-twitter"></i></button> <!--Google +--> <button type="button" class="btn btn-white btn-rounded z-depth-1a"><i … -
Django orm left join queries without foreign keys
This is my SQL query: select (case when a.hosting <= b.yr and (a.hosting * 1000) <= b.yo then 1 else 2 end) as status from a left join b on a.phone_user = b.phone_u and a.per = b.lotus_number; I have tried the following modules: from django.db.models.sql.datastructures import Join from django.db.models.fields.related import ForeignObject I've implemented virtual fields but I don't know how to Join with subtable fields without using loops I want to give me a virtual field, but now that I can't implement it, my mind is in a loop -
TypeError: 'datetime.date' object is not subscriptable
I'm trying to create a custom template tag which takes 3 arguments. I'm trying to calculate the number of days between two dates, while excluding the weekends days from that count. And depending on the department, the weekend is different for each user. So I need start_date, end_date, user_id to be passed onto the template tag function. This is what I have done so far: from django import template from datetime import datetime, timedelta, date register = template.Library() @register.filter('date_diff_helper') def date_diff_helper(startdate, enddate): return [startdate, enddate] @register.filter(name='date_diff') def date_diff(dates, user_id): start_date = dates[0] end_date = dates[1] count = 0 weekends = ["Friday", "Saturday"] for days in range((end_date - start_date).days + 1): if start_date.strftime("%A") not in weekends: count += 1 else: start_date += timedelta(days=1) continue if start_date == end_date: break start_date += timedelta(days=1) return count This is how I'm calling these functions in template: {{ leave.start_date|date_diff_helper:leave.end_date|date_diff:leave.emp_id }} When I run the code, it gives me TypeError saying 'datetime.date' object is not subscriptable. When I tried to check the type of dates parameter in date_diff function, it says: < class 'list'> < class 'datetime.date'> But when it tries to assign start_date as the first date object, as in start_date = dates[0], it throws … -
Does 'creating' a new record override existing ones with same key?
The first code below both creates (if it doesn't exist yet) and override (if it exists) record in db. It's convenient. I would like to know if this creates problem in the DB. I reviewed the table records and it doesn't create duplicates. record = Foo(key='123', value='Hello) record.save() or try: foo_q = Foo.objects.get(key='123') foo_q.value = 'Hello' foo_q.save() except: record = Foo(key='123', value='Hello) record.save() It works but is it safe to continue using or should I query if it exists and update the model. -
Django model: TypeError: 'Manager' object is not callable
I'm developing a Rest API with django. I have this model: from django.db import models from devices.models import Device class Command(models.Model): id = models.AutoField(primary_key=True, blank=True) command_name = models.CharField(max_length=70, blank=False, default='') time = models.DateTimeField(auto_now_add=True, blank=True) timeout = models.TimeField(blank=True) command_status= models.IntegerField(blank=False) tracking = models.IntegerField(blank=False) result_description = models.CharField(max_length=200, blank=False, default='') ssid = models.CharField(max_length=31, blank=False, default='') device = models.ForeignKey(Device, on_delete=models.CASCADE) in the views I have this part of code: @csrf_exempt def command_detail(request, rssid): try: print("Heeeeeeeeeeeeeeeeeeeeeeeeelllo 1111 rssid: ", rssid) commands=Command.objects().filter(ssid=rssid) print("Heeeeeeeeeeeeeeeeeeeeeeeeelllo 2222") command=commands[0] except Command.DoesNotExist: return HttpResponse(status=status.HTTP_404_NOT_FOUND) If I execute my server it works fine without any error but if I trie to test the corresponding server with curl like that: curl -X POST http://127.0.0.1:8000/api/commands/cmdssid1?command_status=40 I get as curl result a so big html indicating an Internal Error in the server and in the django part I got those traces: July 30, 2019 - 08:00:01 Django version 1.10.1, using settings 'project-name.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. ('Heeeeeeeeeeeeeeeeeeeeeeeeelllo 1111 rssid: ', u'cmdssid1') Internal Server Error: /api/commands/cmdssid1 Traceback (most recent call last): File "/path-to-home/.local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/path-to-home/.local/lib/python2.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/path-to-home/.local/lib/python2.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, … -
Exception in thread django-main-thread: TypeError:__init__() got an unexpected keyword argument 'fileno'
I am trying to perform load tests on a django application with locust. However, when I try to perform these with multiple simulated users, I get the following error: Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/<user>/.local/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/home/<user>/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 139, in inner_run ipv6=self.use_ipv6, threading=threading, server_cls=self.server_cls) File "/home/<user>/.local/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 213, in run httpd.serve_forever() File "/usr/lib/python3.6/socketserver.py", line 241, in serve_forever self._handle_request_noblock() File "/usr/lib/python3.6/socketserver.py", line 315, in _handle_request_noblock request, client_address = self.get_request() File "/usr/lib/python3.6/socketserver.py", line 503, in get_request return self.socket.accept() File "/usr/lib/python3.6/socket.py", line 210, in accept sock = socket(self.family, type, self.proto, fileno=fd) TypeError: __init__() got an unexpected keyword argument 'fileno' This error seems very weird to me, because the socket __init__() function is part of a default library in which this error shouldn't occur. I suspect that the error I see here is a red herring, and that the real error is hidden, but I thought that I might as well ask here in case someone knows why this occurs. Some additional information: When I did the load test on django's built-in development server (wsgi) (i.e. started the … -
How to avoid the error This field is required without changing the model field?
How to avoid the error This field is required in modellformset without changing the model fields and allowing to call the form_valid method instead of form_invalid. That is, if the model is created, all fields are required, if the fields are empty, then it simply does not save the model, but validation passes. Now I get that all the forms must be filled in, but the user can only memorize what he needs, and leave the rest empty. Is there a solution? views.py class SkillTestCreateView(AuthorizedMixin, CreateView): model = Skill form_class = SkillCreateForm template_name = 'skill_create.html' def get_context_data(self, **kwargs): context = super(SkillTestCreateView, self).get_context_data(**kwargs)) context['formset_framework'] = SkillFrameworkFormSet(queryset=Skill.objects.none()) context['formset_planguage'] = SkillPLanguageFormSet(queryset=Skill.objects.none()) context['tech_group'] = Techgroup.objects.all() return context def post(self, request, *args, **kwargs): if 'framework' in request.POST: form = SkillFrameworkFormSet(self.request.POST) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(request) elif 'language' in request.POST: form = SkillPLanguageFormSet(self.request.POST) if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(request) else: return self.form_invalid(request) def form_valid(self, form): """If the form is valid, redirect to the supplied URL.""" for form in form: self.object = form.save(commit=False) self.object.employee =Employee.objects.get(pk=self.kwargs['pk']) employee_current_technology = Technology.objects.filter(skill__employee__id=self.kwargs['pk']) if self.object.technology not in employee_current_technology: self.object.save() return redirect("profile", pk=self.kwargs['pk']) def form_invalid(self, request): return render(request, 'skill_create.html', {'formset_framework': SkillFrameworkFormSet(queryset=Skill.objects.none()), 'formset_planguage': SkillPLanguageFormSet(queryset=Skill.objects.none())}) Is the behavior in which I need … -
django templates index of array does not work
Index in templates of django is like this: {{somearray.i}} for my code this is not working!! this is views.py def fadakpage(request): tours = tour.objects.order_by('tourleader') travelers = traveler.objects.order_by('touri') j=0 for i in tours: j+=1 args={'tours':tours,'travelers':travelers,'range':range(j)} return render(request,'zudipay/fadakpage.html',args) this is fadakpage.html / template (it shows empty): {% for i in range %} {{tours.i.tourleader}} {% endfor %} but if i change {{tours.i.tourleader}} to {{tours.0.tourleader}} it works!! i also checked i values and it was true !! -
Improve the calculation of distances between objects in queryset
I have next models in my Django project: class Area(models.Model): name = models.CharField(_('name'), max_length=100, unique=True) ... class Zone(models.Model): name = models.CharField(verbose_name=_('name'), max_length=100, unique=True) area = models.ForeignKey(Area, verbose_name=_('area'), db_index=True) polygon = PolygonField(srid=4326, verbose_name=_('Polygon'),) ... Area is like city, and zone is like a district. So, I want to cache for every zone what is the order with others zones of its area. Something like this: def get_zone_info(zone): return { "name": zone.name, ... } def store_zones_by_distance(): zones = {} zone_qs = Zone.objects.all() for zone in zone_qs: by_distance = Zone.objects.filter(area=zone.area_id).distance(zone.polygon.centroid).order_by('distance') zones[zone.id] = [get_zone_info(z) for z in by_distance] cache.set("zones_by_distance", zones, timeout=None) But the problem is that it is not efficient and it is not scalable. We have 382 zones, and this function get 383 queries to DB, and it is very slow (3.80 seconds in SQL time and 4.20 seconds in global time). is there any way efficient and scalable to get it. I had thought in something like this: def store_zones_by_distance(): zones = {} zone_qs = Zone.objects.all() for zone in zone_qs.prefetch_related(Prefetch('area__zone_set', queryset=Zone.objects.all().distance(F('polygon__centroid')).order_by('distance'))): by_distance = zone.area.zone_set.all() zones[zone.id] = [z.name for z in by_distance] This obviously does not work, but something like this, caching in SQL (prefetch related) the zones ordered (area__zone_set). -
django static files (including bootstrap and javascript) problem
The javascript and CSS files are not properly working in dJango. I have tried all the possible ways to i could have. I have attached Index.html and settings.py files code below. // Index.html {% load static %} <title>Careers &mdash; Website Template by Colorlib</title> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="{% static 'css/custom-bs.css' %}"> <link rel="stylesheet" href="{% static 'css/jquery.fancybox.min.css'%}"> <link rel="stylesheet" href="{% static 'css/bootstrap-select.min.css'%}"> <link rel="stylesheet" href="{% static 'fonts/icomoon/style.css'%}"> <link rel="stylesheet" href="{% static 'fonts/line-icons/style.css'%}"> <link rel="stylesheet" href="{% static 'css/owl.carousel.min.css'%}"> <link rel="stylesheet" href="{% static 'css/animate.min.css'%}"> <link rel="stylesheet" href="{% static 'css/style.css'%}"> <!-- SCRIPTS --> <script src="{% static 'js/jquery.min.js'%}"></script> <script src="{% static 'js/bootstrap.bundle.min.js'%}"></script> <script src="{% static 'js/isotope.pkgd.min.js'%}"></script> <script src="{% static 'js/stickyfill.min.js'%}"></script> <script src="{% static 'js/jquery.fancybox.min.js'%}"></script> <script src="{% static 'js/jquery.easing.1.3.js'%}"></script> <script src="{% static 'js/jquery.waypoints.min.js'%}"></script> <script src="{% static 'js/jquery.animateNumber.min.js'%}"></script> <script src="{% static 'js/owl.carousel.min.js'%}"></script> <script src="{% static 'js/custom.js'%}"></script> // Settings.py STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'bootstrap3', ] -
How to make a model in django without predefined attributes?
I am little bit confused with the django model as the title said. I also cannot find any posts in google. Let's say in the normal way, we will have a model like this: class something(models.Model): fName = models.TextField() lName = models.TextField() ...... lastThings = models.TextField() However, I don't want to have a model like this. I want to have a model with no predefined attributes. In order words, I can put anythings into this model. My thought is like can I use a loop or some other things to create such model? class someModel(models.Model): for i in numberOfModelField: field[j] = i j+=1 Therefore, I can have a model that fit in any cases. I am not sure is it clear enough to let you understand my confuse. Thank you -
Daemonization celery in production
i'M trying to run celery as service in Ubuntu 18.04 , using djngo 2.1.1 and celery 4.1.1 that is install in env and celery 4.1.0 install in system wide . i'm going forward with this tutorial to run celery as service.here is my django's project tree: hamclassy-backend ├── apps ├── env │ └── bin │ └── celery ├── hamclassy │ ├── celery.py │ ├── __init__.py │ ├── settings-dev.py │ ├── settings.py │ └── urls.py ├── wsgi.py ├── manage.py └── media here is celery.py : from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'hamclassy.settings') app = Celery('hamclassy') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() here is /etc/systemd/system/celery.service: [Unit] Description=Celery Service After=network.target [Service] Type=forking User=classgram Group=www-data EnvironmentFile=/etc/conf.d/celery WorkingDirectory=/home/classgram/www/classgram-backend/hamclassy/celery ExecStart=/bin/sh -c '${CELERY_BIN} multi start ${CELERYD_NODES} \ -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' ExecStop=/bin/sh -c '${CELERY_BIN} multi stopwait ${CELERYD_NODES} \ --pidfile=${CELERYD_PID_FILE}' ExecReload=/bin/sh -c '${CELERY_BIN} multi restart ${CELERYD_NODES} \ -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' [Install] WantedBy=multi-user.target and /etc/conf.d/celery: CELERYD_NODES="w1" CELERY_BIN="/home/classgram/www/env/bin/celery" CELERY_APP="hamclassy.celery:app" CELERYD_CHDIR="/home/classgram/www/classgram-backend/" CELERYD_MULTI="multi" CELERYD_OPTS="--time-limit=300 --concurrency=8" CELERYD_LOG_FILE="/var/log/celery/%n%I.log" CELERYD_PID_FILE="/var/run/celery/%n.pid" CELERYD_LOG_LEVEL="INFO" when i run service with systemctl start celery.service the error appear: Job for celery.service failed because the control process exited with error code. See "systemctl status celery.service" and "journalctl -xe" for detail when i … -
Most Pythonic/Django way to dynamically load client libraries at runtime
I'm writing a Django application in which we will have multiple client libraries that make calls to third party APIs. We want to be able to determine which client library to load at runtime when calling different endpoints. I'm trying to determine the most Django/Pythonic way to do this The current idea is to store class name in a model field, query the model in the View, and pass the class name to a service factory that instantiates the relevant service and makes the query. I've also considered writing a model method that uses reflection to query the class name For example lets say we have a model called Exchange that has an id, a name, and stores the client name. class Exchange(models.Model): exchange_name = models.CharField(max_length=255) client_name = models.CharField(max_length=255) def __str__(self): return self.exchange_name Then in the View we might have something like: from rest_framework.views import APIView from MyProject.trades.models import Exchange from django.http import Http404 from MyProject.services import * class GetLatestPrice(APIView): def get_object(self, pk): try: exchange = Exchange.objects.get(pk=pk) except Exchange.DoesNotExist: raise Http404 def get(self, request, pk, format=None): exchange = self.get_objectt(pk) service = service_factory.get_service(exchange.client_name) latest_price = service.get_latest_price() serializer = PriceSerializer(latest_price) return Response(serializer.data) This syntax may not be perfect but it hasn't been … -
Django - Can not upload file using my form
Here's the situation: I'm quite new to Django and I'm trying to upload some files using a form I created. When I click on the submit button, a new line is created in my database but the file I selected using the FileField is not uploaded.But I can upload files via the admin page without any trouble. I've been trying to find a solution for a while now, but I still haven't found anything that could help me, so if one of you has any idea how to solve my problem I would be really thankful. Here you can find some code related to my form: forms.py class PhytoFileForm(forms.ModelForm): class Meta: model = models.PhytoFile fields = ['general_treatment', 'other'] def __init__(self, *args, **kwargs): super(PhytoFileForm, self).__init__(*args, **kwargs) models.py class PhytoFile(models.Model): date = models.DateTimeField("Date", default = datetime.datetime.now) general_treatment = models.FileField("Traitements généraux", upload_to='fichiers_phyto/', blank=True, null=True) other = models.FileField("Autres traitements", upload_to='fichiers_phyto/', blank=True, null=True) class Meta: verbose_name = "Liste - Fichier phyto" verbose_name_plural = "Liste - Fichiers phyto" def __str__(self): return str(self.date) views.py class AdminFichiersPhyto(View): template_name = 'phyto/phyto_admin_fichiers.html' form = forms.PhytoFileForm() def get(self, request): return render(request, self.template_name, {'form': self.form}) def post(self, request): form = forms.PhytoFileForm(request.POST, request.FILES) form.save() return render(request, self.template_name, {'form': self.form}) phyto_admin_fichiers.html {% block forms … -
Throttles connection in day using Djang REST Framework
I want to limit the amount of connection to the web in a day. I have searched on Internet that using Djano REST Throttling, but I don't know how to use Django REST API. I wish I had a sample code to solve the problem. Thanks.