Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Q Object - 'i__contains' to include accents?
i have the following line of code: list = Database.objets.filter(Q(name__icontains=searchstring)) So for example if: searchstring = Georges Méliès It returns the result, but if: searchstring = Georges Melies It doesn't get it. Is there any way i can "tell" Django to ignore accents on letters? Such as here in the case of e? -
display only some objects in change list of a model in django
I am creating a Django application for multiple universities. Here are the Model classes I have used. class Institute(models.Model): name=models.CharField(max_length=200) def __str__(self): return self.name class Applicant(models.Model): name = models.CharField(max_length=200) institute=models.ForeignKey(Institute,on_delete=models.CASCADE) def __str__(self): return self.name I have created a staff user for each institute but the change list of applicants is also showing the applicants who are not of the same institute. I want to modify admin page change list so that it will list only the applicants which belong to that particular institute. Currently my Applicant page change list look like this for every institute from which I have to remove some applicants. Current change list -
Get name of abstract parent model in Django
Suppose I have a set of Django models that are all subclasses of an abstract Base model: from django.db import models class Base(models.Model): created = models.DateTimeField(auto_now_add=True) class Meta: abstract = True class Derived1(Base): name = models.CharField(max_length=32, null=False, unique=True) whatever = models.CharField(max_length=255, null=True, blank=True) Now I can get the Field objects for Derived1 like this: fields=models.Derived1._meta.get_fields() This gives me all the fields, including the inherited "created" field. Once I have this list of fields, is there any way to see that the field "created" was inherited from Base? Does the field object have any function or property that tells me the name of the model on which "created" was defined? Specifically I'm looking for some function field.get_model_name_where_defined() so that for fields defined on Derived1, that function returns "Derived1" but for the "created" field it returns "Base". Does anything like this exist? Just to be clear, I am not looking for a way to assert that Derived1 is derived from Base. What I am looking for is a way to check any Django model and get the unknown name of the model class that is its abstract superclass, if there is such a class. -
How to solve ORA-22284: duplicate LONG binds are not supported error in django
I am using django with oracle database. I have a model that uses django-modeltranslation. When I add text for more than one language oracle database throws ORA-22284: duplicate LONG binds are not supported error. How can I solve it? I am new to StackOverFlow. Please, let me know if my question is not detailed well. This is my model: class About(models.Model): image = models.ImageField(upload_to='about', verbose_name=_('Image')) text = models.TextField(verbose_name=_("Text")) phone = models.CharField(max_length=50, verbose_name="Phone") address = models.CharField(max_length=255, verbose_name=_("Address")) class Meta: verbose_name = _("About") verbose_name_plural = _("About") def __str__(self): return str(_('About AzeriCard')) and this is translations.py from app.models import * from modeltranslation.translator import translator, TranslationOptions class AboutTrans(TranslationOptions): fields = ('text', 'address') -
Messed up Django model PK -- looking to edit the mysql dump file to correct it?
I have a Django project that has been in production use for about 2 years now so there's a bunch of data already on there. One area of the project was started, but never flushed out, and therefore no data was added to all the models of one app in the project. This means there are a handful of tables (models) in this app that aren't used. One model in particular has a problem where a specific field was designated as the PK and isn't auto-increment. I need to change this field so it isn't the primary key, and then let Django create the normal id field that is auto-increment. Since there's data all over this database, here's what I'm thinking of doing: Save the database using mysqldump Edit the Django model so that there's no primary_key=True on any field Remove the migrations for all the apps Edit the mysqldump file so that it will recreate the model in question to match a normal varchar field without setting it as the PK, thereby matching my new model design Add a line to the mysqldump file to create a primary key field of id like Django does for all other models … -
Setting items per page in Django Tastypie Paginator
I am trying to add a custom paginator to my Django API but I am not sure how can I limit the number of items per page in paginator_Class in get_sdc_data(). class CustomApplicationSDCResource(AppMapBaseResource): class Meta(AppMapBaseResource.Meta): #import pdb;pdb.set_trace() queryset = Applications.objects.all() resource_name = 'applications' allowed_methods = {'get'} allowed_models = ['Applications'] paginator_class = Paginator def prepend_urls(self): return [url(r"^(?P<resource_name>%s)/get_sdc_data%s$" % \ (self._meta.resource_name, trailing_slash()), self.wrap_view('get_sdc_data'), name="api_get_sdc_data"), ] def get_sdc_data(self, request, **kwargs): try: sdc_list = [] limit=request.GET.get('limit') next_item = request.GET.get('next') if request.GET.has_key('uaid'): search_uaid=request.GET.get('uaid') sdc_obj = Applications.objects.filter(Q(uaid__contains=search_uaid, status='Active')) else: sdc_obj = Applications.objects.all() exc=['vendor_name', 'ldrps_app_rto','alias_name'] import pdb;pdb.set_trace() sdc_list = [model_to_dict(obj, exclude=exc) for obj in sdc_obj] paginator = self._meta.paginator_class(request.GET, sdc_list, resource_uri=self.get_resource_uri(), \ limit=limit, max_limit=self._meta.max_limit, collection_name=self._meta.collection_name) paginated = paginator.page() paginated['Applications'] = paginated.pop('objects') return self.create_response(request, {"result" : paginated}) except Exception as e: print 'Problem in getting SDC Applications data. Error is ' + str(e) -
Get/display the author of a post from another app for notifications system
So I am making this notification system that is supposed to show/tell the user when someone else has liked or commented on their post. However, instead of telling the user when someone liked your post it instead records your personal activity and shows all of the likes and comments you yourself have made. I know why this is happening (after all I set it up), I just don't know how to reverse it so the post author get's notified instead of the current user. I think I have all the info I need, I just don't know how to go into the other apps model, get the extra bit of info I don't have and then display the notifications for/to the post's author. Please help. Also, please ignore the sloppy imports, I know that needs to be cleaned up. Notify app views: from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger from django.shortcuts import render,get_object_or_404,redirect from django.utils import timezone from feed.models import UserPost,UserComment from users.models import UserProfile from notify.models import UserNotification from feed.forms import PostForm,CommentForm from django.urls import reverse_lazy from django.contrib.auth.decorators import login_required from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from braces.views import SelectRelatedMixin from django.views.generic import (TemplateView,ListView, DetailView,CreateView, UpdateView,DeleteView, RedirectView,) User = get_user_model() … -
django.urls.exceptions.NoReverseMatch: Reverse for 'sign_up' not found. 'sign_up' is not a valid view function or pattern name
Django version 1.11.5, views.py class SignupPage(CreateView): form_class = forms.UserSignupForm success_url = reverse_lazy('login') template_name = 'signup.html' website/urls.py from django.conf.urls import url from django.contrib.auth import views as auth_views from django.contrib.auth.views import LoginView,LogoutView from . import views app_name = 'website' urlpatterns = [ url(r'^login/', auth_views.LoginView.as_view(template_name='signin_2_w.html'), name='login'), url(r'^logout/$', auth_views.LogoutView.as_view(), name='logout'), url(r'^signup/', views.SignupPage.as_view(), name='sign_up'), forms.py class UserSignupForm(UserCreationForm): class Meta: fields = ('username','email','password1','password2') model = get_user_model() def __init__(self,*args,**kwargs): super().__init__(*args,**kwargs) self.fields['username'].label = "Display Name" self.fields['email'].label = "Email Address" self.fields['password1'].label = "Password" self.fields['password2'].label = "Confirm Password" proj/urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$',views.HomePage.as_view(),name='home'), url(r'^website/',include('website.urls',namespace='website')), url(r'^website/',include('django.contrib.auth.urls')), url(r'^website/',views.StreamyePage.as_view(),name='streamye'), url(r'^thanks/$',views.ThanksPage.as_view(),name='thanks'), url(r'^congrats/$',views.CongratsPage.as_view(),name='congrats'), url(r'^aboutus/$',views.AboutusPage.as_view(),name='about_us'), HTML <ul class="nav navbar-nav navbar-right"> {% if user.is_authenticated %} <li><a href="{% url 'logout' %}">Logout</a></li> {% else %} <li><a href="{% url 'login' %}">Login</a></li> <li><a href="{% url 'sign_up' %}">Signup</a></li> {% endif %} </ul> In the above code, the signup page is throwing me a error -- "django.urls.exceptions.NoReverseMatch: Reverse for 'sign_up' not found. 'sign_up' is not a valid view function or pattern name." Please someone help me out where im wrong! Thanks in advance! -
django mysql-client or mysql-db error
I am facing these errors when I am running the python manage.py runserver Also i have tried: 1.pip install MySQL-python 2.pip install mysql-python but nothing worked.I need help Errors i am getting -
Success message not displayed in Django ClassBasedView
I am trying to display success message after saving form. I am using message framework for this settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_PATH], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] views.py class VolunteerCreateView(SuccessMessageMixin, CreateView): model = Volunteer form_class = VolunteerForm template_name = 'volunteer.html' success_message = 'Thank you!' success_url = reverse_lazy('volunteer') volunteer.html {% if messages %} <div class="alert center block" role="alert"> <ul class="messages"> {% for message in messages %} <li class="text-center"{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> </div> {% endif %}..... But the message is not displayed. I can see the message json on request header in redirected url but is not displayed. Part of request header Cookie:olfsk=olfsk1757071755791586; hblid=HecPjm2lDQ2xTzgn3m39N0J00JEB6o1A; sessionid=z8zh4t13mw655mf3yn1vfnow8y58zxt9; csrftoken=GZxsdPZmBsefPU0nv7ZEfEaxsnPCMjIehpiFihY3GtTrhFnuFc5c3NXplD35Qslw; ext_name=jaehkpjddfdgiiefcnhahapilbejohhj; messages="ab8f5c6976dd0939d4f1b867ca564577ba9cc0d7$[[\"__json_message\"\0540\05425\054\"Thank you!\"]]" What could be the reason that message is not displayed. Is there anything I am missing. -
How to implement an activity feed/notifications system?
I'm using redis and know how to make an activity feed but like in Instagram if let say 20 users liked your feed, it just shows JOHN Mike and 18 others liked your picture I have been able to show all 20 but don't know how to implement this kinda feature I don't need the code I just need to understand the logic behind this Thanks -
Django makemigrations works but migrate doesn't
I've an app which I've just putting onto a VPS to test. It works fine on my PC (Ubuntu) using the manage.py runserver When I try and put it on the server I get the following error/traceback: Applying listing_cms_integration.0002_auto_20171017_1634...Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/var/www/listty/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/var/www/listty/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/var/www/listty/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 305, in run_from_argv self.execute(*args, **cmd_options) File "/var/www/listty/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 356, in execute output = self.handle(*args, **options) File "/var/www/listty/env/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 202, in handle targets, plan, fake=fake, fake_initial=fake_initial File "/var/www/listty/env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 97, in migrate state = self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File "/var/www/listty/env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 132, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/var/www/listty/env/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 237, in apply_migration state = migration.apply(state, schema_editor) File "/var/www/listty/env/local/lib/python2.7/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/var/www/listty/env/local/lib/python2.7/site-packages/django/db/migrations/operations/fields.py", line 204, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/var/www/listty/env/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 495, in alter_field old_db_params, new_db_params, strict) File "/var/www/listty/env/local/lib/python2.7/site-packages/django/db/backends/sqlite3/schema.py", line 255, in _alter_field self._remake_table(model, alter_fields=[(old_field, new_field)]) File "/var/www/listty/env/local/lib/python2.7/site-packages/django/db/backends/sqlite3/schema.py", line 186, in _remake_table self.alter_db_table(model, temp_model._meta.db_table, model._meta.db_table) File "/var/www/listty/env/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 372, in alter_db_table "new_table": self.quote_name(new_db_table), File "/var/www/listty/env/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 112, in execute cursor.execute(sql, params) File "/var/www/listty/env/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 79, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/var/www/listty/env/local/lib/python2.7/site-packages/django/db/backends/utils.py", … -
Django SMTP [Errno 111] Connection refused
I am trying to send email from a web app using django and a sendgrid SMTP server. It works fine locally but when I try to use it on pythonanywhere I get error: [Errno 111] Connection refused The code from the relevant view is def contact(request): if request.method == 'POST': form = EmailForm(request.POST) if form.is_valid(): mail = form.cleaned_data send_mail( 'Automated Enquiry', 'A user is interested in part ' + mail['part'] + '.Their message: ' + mail['msg'], mail['email'], ['myemail@gmail.com'], fail_silently = False, ) return render(request, 'manager/error.html', {'msg': "Thanks, we will be in touch as soon as possible"}) else: part = request.GET.get('part', '') form = EmailForm() return render(request, 'manager/contact.html', {'form': form, 'part':part}) And in my setting.py: EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER = 'myuser' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_PORT = 587 EMAIL_USE_TLS = True It didn't work from the console either. Any help would be greatly appreciated. -
Django: get related objects of related objects and pass to template
In a Django app I have three models: class A(models.Model): aId = models.AutoField(primary_key=True) class B(models.Model): bId = models.AutoField(primary_key=True) aId = models.ForeignKey(A) class C(models.Model): cId = models.AutoField(primary_key=True) bId = models.ForeignKey(B) There is a on-to-many relation between A and B, as there is between B and C. And there is a View class with context_data. In the template I need to show and filter Bs, with their Cs. How can I pass All Bs related to an A and All Cs related to those Bs to my template (context)? I tried to get Bs and Cs separately in two arrays, but it seems not to be a good idea because I can not categorize Cs by Bs. -
How to easily add Django urls?
I am working on a website, very basic, just HTML and CSS. Its all static and I'm needing to add more urls. I have read the Django documentation and it isnt quite clicking with me. What I have is my home page and I need to be able to click the link on my navbar and be taken to the next page. I'm just not sure how to add another URL in django. Thank you in advance! Sorry if I missed anything. It's my first post -
Editable but not changeable foreign keys in django admin
In Django admin, you can mark fields as readonly, including Foreign Key fields. A regular ForeignKey field gets both a pencil to let you edit the current object being pointed to, and a dropdown/plus to let you point to another object. I'd really like a ForeignKey field that has the pencil but not the dropdown/plus. That is, I'm fine with the admin allowing editing of the thing I'm pointing to, but not changing what I'm pointing to. Is there an easy way to do this? -
django: generate external .html file with external .css files
I'm relatively new to django and am having an issue including static css files (like bootstrap, font-awesome) into a html file that I'm writing as an external output file (which I then need to open with MS Word - that's the endgame). The html that I render to the browser is fine, but when I write it to a file for a download link that I'm implementing, it's not "including" the static files, just the links. The download is also working for the .html file generated. Is there any way to flatten these styles as they are rendered with the django dev server so Word will recognize the styles? I've tried using the cdn and just including my local styles in the header, but the html generated is using the link rel="stylesheet", so they are not being "pulled into" the generated html when downloaded as a file. Thanks for any pointers/assistance! Really appreciated! -
Getting 404 not found when working with docker container nginx uwsgi django
I'm having 3 docker containers. One container has Django with uwsgi and nginx. I configure inside with 80 port exposed. And later run with 8800:80 mapping in my localhost. A second container has another Django project with uwsgi and nginx, similar configuration and run with 8801:80 mapping in my localhost. So right now I can access different Django apps from the container with different ports. localhost:8800 -> app1 localhost:8801 -> app2 now I create a third container with nginx, which aims to do the reverse proxy. So I third container has only nginx configuration. Which has something like this: error_log /var/log/nginx/error.log; events { worker_connections 1024; } http { sendfile on; gzip on; gzip_http_version 1.0; gzip_proxied any; gzip_min_length 500; gzip_disable "MSIE [1-6]\."; gzip_types text/plain text/xml text/css text/comma-separated-values text/javascript application/x-javascript application/atom+xml; upstream app1{ server my_machine_ip:8800; } upstream app2{ server my_machine_ip:8801; } access_log /var/log/nginx/access.log; server { listen 0.0.0.0:80; location /firstapp/ { proxy_pass http://app1/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } location /anotherapp/ { proxy_pass http://app2/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } } Again the container with 80 port expose and I run with port 8888:80 mappings. Then I have … -
uWSGI uses Python 2.7 instead of 3.5 which causes consequential errors
I'm trying to create a Django app with WebSockets on a Raspberry Pi 2 using django-websocket-redis pip package. /manage.py runserver doesn't seem to work (got 404 calling /ws/ although it's set by WEBSOCKET_URL = '/ws/' in settings.py), I wanna try a standalone uWSGI server like described here in the official docs. When I run uwsig, I got strange errors. I think this is caused by a wrong python version. The output of uwsig show me that Python 2.7 is used: Python version: 2.7.13 (default, Jan 19 2017, 14:48:08) [GCC 6.3.0 20170124] But I need Python 3 (exactly 3.5) for my project. I changed the default python environment, so that the python comamnd points to python 3.5 instead of 2.7. Additionally, I passed the version using --plugin switch like this: uwsgi --http :9090 --plugin=python35 --wsgi-file wsgi.py I also used pip3for all pip packages to make sure that no 2.x packages were used. This seems having no effect, cause my script breaks and uwsgi show me that Python 2.7 is used... -
Update object value from function based view
I have a django project that has a form with two buttons in one of my templates. These buttons either accept or decline an "Offer", which is one of my models. I pass a POST request from the template to the view where i have two functions. How do i make these approve and decline buttons update the value "approved_by_x" in my model? The Template: <form method="post" class="login-container" action="{% url 'accept_booking' %}"> {% csrf_token %} <input class="btn btn-primary" type="submit" value="Accept" name="Accept"/> <input type="hidden" name="offer" value="{{ offer }}" /> </form> <form method="post" class="login-container" action="{% url 'decline_booking' %}"> {% csrf_token %} <input class="btn btn-primary" type="submit" value="Decline" name="Decline" /> <input type="hidden" name="offer" value="{{ offer }}" /> </form> The View: def accept_booking(pr): offer = pr.POST.get("offer") print(offer) def decline_booking(pr): offer = pr.POST.get("offer") print(offer The Model: class BookingOffer(models.Model): artist = models.ForeignKey(Artist, null=True, related_name='artist') artist_manager = models.ForeignKey(User, default=1, limit_choices_to= {'groups__name': 'artist_manager'}) comment = models.TextField(max_length=120, blank=True) time_slot = models.ForeignKey('TimeSlot', null=True, blank=True) price = models.IntegerField(null=True, blank=True) tech_needs = models.TextField(blank=True) approved_by_bm = models.BooleanField(default=False) accepted_by_am = models.BooleanField(default=False) -
Django slow to delete rows based on Foreign Key when rows are not created through ORM
I'm encountering a situation where Django is slow to delete rows from a table when they are related to another table via a Foreign Key (FK), but were not created via the Django ORM. I have the following Django model for Record: class Record(models.Model): job = models.ForeignKey(Job, on_delete=models.CASCADE) index = models.IntegerField(null=True, default=None) record_id = models.CharField(max_length=1024, null=True, default=None) document = models.TextField(null=True, default=None) error = models.TextField(null=True, default=None) This is related to the model Job via the job column (job_id in MySQL after Django migration creation). However, Record rows are not written via Django, but instead from Apache Spark via jdbc.write(). A typical example might be 1 Job with 45k related Record rows. The problem is, while deleting a Job instance via the Django ORM via job.delete() does delete the associated Record rows, it is quite slow, 5-7 seconds for 1 Job with 45k associated Record rows, 20-30 seconds for 160k, and so forth. My understanding is that Django emulates ON DELETE CASCADE to accommodate different DB backends, which makes sense. But I'm wondering: if the Record rows are not created via the Django ORM, does that bypass some kind of internal Django indexing that would otherwise make this cascading deletion of associated … -
Django & Postgresql annotate datetime field to localtime
I'm using Django 1.11 with Postgresql 9.6 and JQuery DataTables (using django-datatables to provide AJax datasource from Djang model. Model example: class MyModel(models.Model): start = models.DateTimeField() end = = models.DateTimeField() Postgresql stores the datetimes in UTC with timezone info, which is fine. I can override the DataTables render column to render the datetime correctly in the DataTables view: if column == "start": return timezone.localtime(row.start).strftime(STRFTIME_DATETIME_FORMAT) The problems when trying to provide the search filter query for partial dates. If I add an annotation to add date_str to search on: def filter_queryset(self, qs): search = self.request.GET.get(u'search[value]', None) if search: sql_datetime_format = getattr(settings, "SQL_DATETIME_FORMAT", "DD/MM/YYYY HH24:MI") qs = qs.annotate( start_str=Func(F('start'), Value(sql_datetime_format), function='to_char'), end_str=Func(F('end'), Value(sql_datetime_format), function='to_char'), ) q_objects = Q() q_objects |= Q(start_str__icontains=search) q_objects |= Q(end_str__icontains=search) qs = qs.filter(q_objects).distinct() return qs The start_str and end_str are converted to strings as UTC datetimes not local datetimes. So I UK date in summer displays correctly as 01/06/2017 00:00, but to search for it you have to enter: 31/05/2017 23:00 I can't seem to find away to get start_str and end_str to local time instead of UTC. -
how to calculate field in django admin model
i have a model that i have added to my django admin panel from django.db import models from django.contrib import admin class Employee(models.Model): fee = models.IntegerField(null=False) vat = models.IntegerField(null=False) and have added this my admin panel admin.site.register(Employee, EmployeeAdmin) readonly_fields('vat',) so while adding a new employee, the admin inputs the fee amount, id like vat to be calculated and shown as a direct result of entering the vat. how can create this calculation on the fly as the admin is entering the fee -
Django - Remove object from database after day
I want to remove object after one day. Here is part of my code: data = models.DateField(null=True) So for example value of data field is 10.10.2017 And I want to remove it in 11.10.2017 Thanks for help ! -
Passing User object in celery using django
I'm currently editing the save method in one of my models, so that I can save who changed an object or created a new one. Currently, its working fine when its ran in the main thread, but the save method is also used in different tasks through Celery. And when the save method is ran in a task get user returns None. To get a user i'm currently using django-curser since this model is being used in different apps inside my Django project. Is there a way to send the current user to celery? I've been told to use a context manager or a wrapper but im not sure how. My save method is: def save(self, *args, **kwargs): from models import Log log_entry = Log() log_entry.object_id = self.id log_entry.object_repr = self user = CuserMiddleware.get_user() log_entry.user = user log_entry.content_type_id = ContentType.objects.get_for_model(self).id log_entry.save() Thanks.