Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to fix pyinotify Error
I get a pyinotify error that makes my code unable to import my models. Here is the log [2017-10-18 10:31:20,835 pyinotify ERROR] The pathname '/home/PycharmProjects/bookshop/bookshelf/search.py' of this watch <Watch wd=850 path=/home/PycharmProjects/bookshop/bookshelf/search.py mask=4038 proc_fun=None auto_add=False exclude_filter=<function <lambda> at 0x7f001f8210c8> dir=False > has probably changed and couldn't be updated, so it cannot be trusted anymore. To fix this error move directories/files only between watched parents directories, in this case e.g. put a watch on '/home/PycharmProjects/bookshop/bookshelf'. Unhandled exception in thread started by <function wrapper at 0x7f1deeb6c848> I am trying to implement elastic search on a simple django model but it seems like the index don't form because it can't even find the model. any Idea how to solve this according to the message To fix this error move directories/files only between watched parents directories I don't really understand what it means by watched parents. I am running on OS-->Kali Linux IDE-->Pycharm If you need more info on this error please let me know -
page not found createsuperuser commond - django
when I enter createsuperuser command and then runserver one in cmd, I got the following error: url not found my url: localhost:8000/admins my urls.py: from django.conf.urls import url from django.contrib import admin from . import views urlpatterns = [ url(r'^$', views.index, name = 'index'), ] my settings.py: DEBUG = False ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admindocs', ] where is my problem? I think everything is well. -
Django query does not select related_name
I do have the following models in django: class UserPayments(models.Model): _DATABASE = "payments" id = models.AutoField(primary_key=True) paym_psp_id = models.ForeignKey(ConfigPSP, null=True, on_delete=models.SET_NULL) [...] class InvoiceNumbers(models.Model): _DATABASE = "payments" id = models.AutoField(primary_key=True) inv_date = models.DateField(null=False) inv_payment_id = models.ForeignKey(UserPayments, null=True, on_delete=models.DO_NOTHING, related_name='paym_invoice_meta') [...] As you can see they are related with "related_name" definition in the InvoiceNumbers model. When I no do a query in django like: payments = UserPayments.objects.filter(paym_user_id=user_id) And iterate through this query in a template {% for inv in payments %} {% for meta in inv.paym_invoice_meta %} {{ meta.inv_invoice_hash }} {% endfor %} {% endfor %} I get the template error that pay_invoice_meta is not iterable. With a manual select statement including the left outer join I get all the results. What am I missing here? How can I force the query to select the values from InvoiceNumbers? -
'urlname' is not a valid value for a primary key
I have looked to all questions asked in SO about this issue but no one seems to be appropriate to my case. I have a search form containing a field of a foreign key. this is the model : class A(models.Model): sa_datetime = models.DateTimeField(help_text='Start Date & Time') b= models.ForeignKey('B', help_text='B') class B(models.Model): start_datetime = models.DateTimeField(help_text='Start Date & Time') url= models.CharField(help_text='url', max_length=50) and this is the search form : class SearchForm(forms.Form): start_datetime = forms.DateField( label=_("Start Date"), required=False, widget=customDateInput() ) url= forms.ModelMultipleChoiceField( label=_("URL"), required=False, queryset=B.objects.filter(url__isnull=False).values_list('url',flat=True), widget=forms.SelectMultiple( attrs={ "class": "selectpicker form-control", "data-live-search": "true" } ) ) and this my view : class ASearchView(SearchView): template_name = "aa/aa_list.html" model = A form_class = SearchForm foreignFields = ["b"] def get_queryset(self): start_datetime = self.request.GET.get('start_datetime') url = self.request.GET.get('url') res= A.objects.select_related("b") if url: print 'heeeeeeeeeeeeereeeeee' res= res.filter(b__url=url) return res I use a generic search form in my template , I just have to set the variables : {% with 'A_list' as model_index_url %} {% with 'B_search_view' as model_search_url %} {% with item_count=paginator.count app_name='name_app' model_name='A' %} {% include 'name_app/search_form_wrapper.html' %} {% endwith %} {% endwith %} {% endwith %} the values of url are displayed properly in the multiple select field ,but I inspected the code and I have figured … -
Create Django QuerySet from Orcale table-valued Function
I try to create a Django QuerySet from an Oracle table-valued Function qs = MyModel.objects.raw("SELECT * FROM TABLE(My-table-valued-Function)") As soon as I evaluate the query set I get the error: django.db.utils.DatabaseError: ORA-00942: table or view does not exist Does anybody have a solution for this? Thanks! Thorx -
Technology stack for handling CSV files online
just starting here and learning how to code. I have found an interesting project to start me on the coding journey but not too sure about choice of technology. These are the user description steps to the project: User uploads a pre-formatted file to the cloud/online database repository/whatever you want to call it Based on a set of pre-determined rules (chosen by the user and/or determined beforehand by developer) this file is analysed and respective comments are generated The user downloads a text file with the generated comments Happy to take advice on any pros and cons of different technology stacks. Timeframe for the project is 12 months (including learning a new language if necessary). -
FileUploadParser doesn't get the file name
I just want to create a REST API that receives a file, process it and return some information. My problem is that I am following this example: http://www.django-rest-framework.org/api-guide/parsers/#fileuploadparser And I can't make it work using Postman or curl, I think I am missing something. The parser always gives me these two errors: FileUpload parse error - none of upload handlers can handle the stream Missing filename. Request should include a Content-Disposition header with a filename parameter. This is the code: views.py: class FileUploadView(APIView): parser_classes = (FileUploadParser,) def post(self, request, filename, format=None): file_obj = request.data['file'] # ... # do some stuff with uploaded file # ... return Response(status=204) def put(self, request, filename, format=None): file_obj = request.data['file'] # ... # do some stuff with uploaded file # ... return Response(status=204) urls.py urlpatterns = [ url(r'predict/(?P<filename>[^/]+)$', app.views.FileUploadView.as_view()) ] settings.py """ Django settings for GenderAPI project. Generated by 'django-admin startproject' using Django 1.9.1. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os import posixpath LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'debug.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', … -
Django deep admin.TabularInline
if there is relation like: django can show it in one admin page by TabularInline: admin.py from django.contrib import admin from myapp2 import models # Register your models here. class TabularInlineB(admin.TabularInline): model=models.B class AdminA(admin.ModelAdmin): inlines=[TabularInlineB, ] admin.site.register(models.A, AdminA) models.py from django.db import models # Create your models here. class A(models.Model): name=models.CharField(max_length=10) class B(models.Model): name=models.CharField(max_length=10) a=models.ForeignKey(A) .the output is like: but if we add another ForeignKey relation to B like below, then How I can show all models in one page? admin.py from django.contrib import admin from myapp2 import models class TabularInlineC(admin.TabularInline): model=models.C class TabularInlineB(admin.TabularInline): model=models.B inlines=[TabularInlineC, ] class AdminA(admin.ModelAdmin): inlines=[TabularInlineB, ] admin.site.register(models.A, AdminA) .models.py from django.db import models # Create your models here. class A(models.Model): name=models.CharField(max_length=10) class B(models.Model): name=models.CharField(max_length=10) a=models.ForeignKey(A) class C(models.Model): b=models.ForeignKey(B) name=models.CharField(max_length=10) the output dose not show C: -
Django programming - how to redirect to original url
I have a website www.example.com with many pages. On each page I put one special unique button, which link to unique URL www.example.com/task1. Once click this button, Django urls patten will pass it to dedicated function task1 for me. My question is how to refresh original URL after completion of the task1, I find request.path only could transfer /task1. Any idea to get back the URL which the button allocated. Please refer to my task1 function. def task1(request): ''' do task1 job ''' return render(request, request.path) # above return could not render the original URL which I clicked from. -
Using Redshift's native 'AT TIMEZONE' through django query?
So I have this query which goes like query = MyModel.objects.filter(some_filter).filter(eventTime__date__gte=start_date).filter(eventTime__date__lte=end_date).... The redshift table I am connecting to has eventTime as UTC. It offers me to query in native SQL like select eventtime AT TIME ZONE 'MST' from mymodel limit 1; How can I use that AT TIME ZONE 'MST' in django query format? -
'collections.OrderedDict' object has no attribute 'pk' - django rest framework
I have a model and I want to write an update() method for it in order to update. The below snippet is my model: class Klass(models.Model): title = models.CharField(max_length=50) description = models.CharField(max_length=500) university = models.CharField(max_length=50,blank=True, null=True) teacher = models.ForeignKey(Profile, related_name='teacher', on_delete=models.CASCADE) and the below snippet is corresponding Serializer: class KlassSerializer(ModelSerializer): teacher = ProfileSerializer() url = HyperlinkedIdentityField(view_name='mainp-api:detail', lookup_field='pk') klass_settings = KlassSettingsSerializer() class Meta: model = Klass fields = ('url', 'id', 'title', 'description', 'university','teacher') def update(self, instance, validated_data): instance.title = validated_data.get('title', instance.title) instance.description = validated_data.get('description', instance.description) instance.university = validated_data.get('university', instance.university) instance.save() return instance And for update, I use below snippet: class KlassAPIView(APIView): def put(self, request, pk=None): if pk == None: return Response({'message': 'You must specify class ID'}, status=HTTP_400_BAD_REQUEST) klass = Klass.objects.get(pk=pk) if request.user.profile.type != 't': raise PermissionDenied(detail={'message': 'You aren't teacher of this class, so you can't edit information.'}) serializer = KlassSerializer(data=request.data, context={'request': request}) serializer.initial_data['teacher'] = request.user.profile.__dict__ if serializer.is_valid(): serializer.update(instance=klass, validated_data=serializer.data) # Retrieve teacher and store return Response({'data': serializer.data}, status=HTTP_200_OK) else: return Response({'data': serializer.errors}, status=HTTP_400_BAD_REQUEST) but when I send data with PUT method, it returns below error: AttributeError at /api/class/49/ 'collections.OrderedDict' object has no attribute 'pk' and the error occurs in serializer.update(instance=klass, validated_data=serializer.data) line. -
Restart postgres connection in django
I have very strange situation here. Problem: I describe original problem inside this post, but to sum up: After using the project for a while, makemigrations stop working for me. (Yes I have set everything ok, setting are ok,.. please see my comments on previous post) I decided that I can't figure this out, so I would start fresh. (thats why git is for :D ) So, I delete my django project, I create new virtual environment, and I also create new database and new user in postgres. I update new database parameter inside my config file and try to run initial makemigrations but with no luch. It is still say that no new migrations are available. I am desperate because I can't work on the project, so any solution would do :D (virtual_environment) MacBook-Pro-2:MY_PROJECT marko$ python manage.py makemigrations connectors environment=local I will use local settings. No changes detected in app 'connectors' All my migrations (virtual_environment) MacBook-Pro-2:MY_PROJECT marko$ python manage.py showmigrations environment=local I will use local settings. admin [X] 0001_initial [X] 0002_logentry_remove_auto_add auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length connectors (no migrations) contenttypes [X] 0001_initial [X] 0002_remove_content_type_name sessions [X] 0001_initial … -
How to query translatable fields with graphene
Assuming a model that has translated fields like below, how can we query these with django-graphene? from parler.models import TranslatableModel, TranslatedFields class Article(TranslatableModel): #regular fields publishing_date = models.DateTimeField(_('publishing date'), default=now) # translated fields translations = TranslatedFields( title=models.CharField(_('title'), max_length=234), slug=models.SlugField( verbose_name=_('slug'), max_length=255, db_index=True, blank=True, ), meta_title=models.CharField( max_length=255, verbose_name=_('meta title'), blank=True, default=''), meta_description=models.TextField( verbose_name=_('meta description'), blank=True, default=''), meta_keywords=models.TextField( verbose_name=_('meta keywords'), blank=True, default=''), ) For registering "unknown" fields I do something like: @convert_django_field.register(TaggableManager) def convert_tagfield_to_string(field, registry=None): return graphene.String(description=field.help_text, required=not field.null) ... but this won't work here. Any ideas? -
How to actualize Django Template with get_context_data
I need your help in order to know How I can actualize my Django template from get_context_data. I have this class in my view : class IdentitySocieteResumeView(LoginRequiredMixin,TemplateView) : template_name = 'Identity_Societe_Resume.html' model = Societe def get_context_data(self, **kwargs) : context_data = super(IdentitySocieteResumeView, self).get_context_data(**kwargs) id = self.kwargs['id'] societe = get_object_or_404(Societe, pk=id) obj = Societe.objects.filter(Nom=societe.Nom, SIRET=societe.SIRET, SIREN=societe.SIREN, Ville=societe.Ville) if obj: sc_obj = obj[0] NIU = lib.Individu_Recherche.NIUGeneratorSociete(ModelBase=societe) societe.NumeroIdentification = NIU societe.save() context_data['queryset'] = obj return context_data And this important function in lib.Individu_Recherche : def NIUGeneratorSociete(ModelBase) : create_year_temp = str(ModelBase.Creation.year) create_year_temp2 = str(create_year_temp.split(" ")) create_year = create_year_temp2[4] + create_year_temp2[5] ''' A process which let to generate NumeroIdentification ''' NumeroIdentification = force_text('%s-%s%s-%s-%s-%s' % ('E', create_year, create_month, create_city, key, create_country_id)) return NumeroIdentification I'm sure my template is loaded before to execute this function and I get in my template NumeroIdentification = None but in my database this field is well-filled. My question is : How I can display my variable NumeroIdentification with the good value in my template (value stored in my database) instead of None ? If I press Cmd + R (MacOS Actualize), NumeroIdentification won't be None but a different value. I would like to get this value in my template the first time. It's … -
How create 2 step registration on python django without asking password fields at any step
Hello I am new at Django developing. I am trying to create 2 step registration for my django app. Here my code: forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class RegisterFpForm(UserCreationForm): email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email adress.') first_name = forms.CharField(max_length=30, help_text='Example:Tosko') last_name = forms.CharField(max_length=30, help_text='Example:Yosko') gender = forms.CharField(max_length=10, help_text='Male/Female') class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'gender', ) class RegisterSpForm(UserCreationForm): country = forms.CharField(max_length=100, help_text='Example:Ukraine') city = forms.CharField(max_length=100, help_text='Example:Kiev') address = forms.CharField(max_length=200, help_text='Example:Marshala Timoshenko street') mobile_phone = forms.CharField(max_length=10, help_text='Example:0631231515') class Meta: model = User fields = ['country', 'city', 'address', 'mobile_phone',] RegistrationFpForm its a First step and RegistrationSpForm is Second Step views.py from django.shortcuts import render # Create your views here. from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.contrib.auth import login, logout, authenticate from .forms import RegisterFpForm, RegisterSpForm def logout_vw(request): """Logout link""" logout(request) return HttpResponseRedirect(reverse('testreg:index')) def register(request): """Register new user""" if request.method != 'POST': form = RegisterFpForm() else: form = RegisterFpForm(data=request.POST) if form.is_valid(): new_user = form.save() return HttpResponseRedirect(reverse('users:register_next')) context = {'form': form} return render(request, 'users/register_f.html', context) def register_next(request): """Continue register new user""" if request.method != 'POST': form = RegisterSpForm() else: form = RegisterSpForm(data=request.POST) if form.is_valid(): new_user = … -
Why is a unique required CharField not giving a IntegrityError when empty?
With the following model: class Client(models.Model): name = models.CharField(max_length=50, unique=True) created_at = models.DateTimeField(auto_now_add=True, editable=False) modified_at = models.DateTimeField(auto_now=True, editable=False) This test fails: def test_no_name_error(self): '''Ensure an Error is raised when creating a client with no name ''' with self.assertRaises(IntegrityError): client = Client.objects.create() The test fails with: FAIL: test_no_name_error (projects.tests.test_models.ClientModelTests) Ensure an Error is raised when creating a client with no name ---------------------------------------------------------------------- client = Client.objects.create() AssertionError: IntegrityError not raised I am using mysql -
Custom django field type, with modified column look up in SELECT part
I would like to implement a custom Django field type. Namely a TranslatedField that is backed by native json/jsonb using postgres. But I would also like it to not have to return all translations for a particular query. Something like this: class TranslatedField(JSONField): pass class MyModel(models.Model): name = TranslatedField() And then used in an example: >>> MyModel.objects.create(name={'en': 'Duck', 'fr': 'Canard'}) >>> set_language('fr') # Imagine this function sets a global variable >>> en_fr = MyModel.objects.get(id=1) >>> en_fr.name >>> 'Canard' Which is fine, I can do that by returning the whole 'name' json from the database. But I would prefer if django issued actual SQL like this that did the lookup in postgres and saved me some bytes across the network: SELECT 'name'->'fr' FROM 'mymodel'; Does Django have any hooks that let me dynamically change the 'SELECT' part of the query? -
Change default GeoModelAdmin to OSMGeoAdmin
I tried to just naively to add it to admin.py like I normally would. from django.contrib.gis import admin from project.models import ProjectMap admin.site.register(ProjectMap, admin.OSMGeoAdmin) But it stil just show the default satellite image GeoModelAdmin. Here is the basic models i'm working with. class ProjectPage(Page): date = models.DateField("Post date", null=True) body = RichTextField(blank=True) def main_image(self): gallery_item = self.gallery_images.first() if gallery_item: return gallery_item.image else: return None search_fields = Page.search_fields + [ index.SearchField('body'), ] content_panels = Page.content_panels + [ MultiFieldPanel([ FieldPanel('date'), ], heading="Project information"), MultiFieldPanel([ FieldPanel('body', classname="full"), ], heading='Project'), InlinePanel('gallery_images', label="Gallery images"), InlinePanel('project_map', label="Project location") ] class ProjectMap(Orderable): page = ParentalKey(ProjectPage, related_name='project_map') city = models.CharField(blank=True, max_length=250) address = models.CharField(blank=True, max_length=250) country = models.CharField(blank=True, max_length=250) location = PointField(blank=True, null=True) content_panels = Page.content_panels + [ MultiFieldPanel([ FieldPanel('city'), FieldPanel('address'), FieldPanel('country'), FieldPanel('location'), ], heading="Location") ] Can I specify something like this in? content_panels = Page.content_panels + [ FieldPanel('location'), ] Or how do one go about this? I can't find it in the documentation. -
Upload and save multiple images using a csv with Django
I am trying to save multiple images to my DB (reference to their path) and upload them to my server via a csv containing the paths and attributes of the images (location where the image was took) but I don't know how and I couldn't find documentation for this particular feature. imagelist.csv imgpath,destination G:/Images/sunsetparis.jpg,Paris France G:/Images/image1.jpg,Berlin Germany G:/Images/_DS001.jpg,Tokyo Japan G:/Images/_DS002.jpg,Sydney Australia G:/Images/image2.png,Rio Brazil I want to parse this list and upload the images and save the names and destination to a DB forms class CSVForm(forms.Form): file = forms.FileField()# to upload the csv I used pandas to read the csv but I am stuck at this point, don't know how to save the images and the attributes views def CSVFormView(request): form = CSVForm() if request.method == "POST": form = CSVForm(request.POST, request.FILES) if form.is_valid(): file = request.FILES['file'] data = file.read() df = pd.read_csv(io.BytesIO(data)) for index, row in df.iteritems(): print(row) ### don't know how to proceed from here Can you please lend a helping hand? Thank you -
Django: annotate Count with filter
I have "post" objects and a "post like" object with how many likes a post has received by which user: class Post(models.Model): text = models.CharField(max_length=500, default ='') user = models.ForeignKey(User) class PostLike(models.Model): user = models.ForeignKey(User) post = models.ForeignKey(Post) I can select how many likes a post has received like this: Post.objects.all().annotate(likes=Count('postlike')) This roughly translates to: SELECT p.*, Count(l.id) AS likes FROM post p, postlike l WHERE p.id = l.post_id GROUP BY (p.id) It works. Now, how I can filter the Count aggregation by the current user? I'd like to retrieve not all the likes of the post, but all the likes by the logged user. The resulting SQL should be like: SELECT p.*, Count(l.id) AS likes FROM post p, postlike l WHERE p.id = l.post_id AND l.user_id = 42 GROUP BY (p.id) -
I want an async response from view and show it as api response came
I have one view that calls 7 APIs and in the view, it loads all the 7 response and send to the templates but the problem is its first waits for all API to respond and then send the response to template and what I want is if one API responded then go to template and show the result second loads show the result like that so the waiting time is not as much as 7 APIs. here is my code : class Analyze(View): def post(self, request): if 'get_report' in request.POST: # Get site detail site_id = self.request.session.get('client_site_id') site = Site.objects.filter(id=site_id).first() # If couldn't find site than take the user to first step if not site: return redirect('analyze-site') self.context['get_report_form'] = GetReportForm(request.POST) # If valid email than generate & send PDF to user if self.context['get_report_form'].is_valid(): # Attach the email with site report site.email = self.context['get_report_form'].cleaned_data['email'] site.save() # generate the report is_generated, report_path, report_message, error = generate_site_report(site) if is_generated: # Send report via email is_email_sent, email_report_message, error = email_site_report(site) if is_email_sent: self.context['get_report_success'] = email_report_message # Clear the get report form self.context['get_report_form'] = GetReportForm() else: logger.error('Failed to email report of site - {id} due to {error}'.format(id=site.id, error=error)) self.context['get_report_error'] = email_report_message else: logger.error('Failed to … -
Django pass datetime via ajax
views.py cases = Case.objects.filter(Customer = customer) for item in cases: localtime = datetime_handler(item.CreatedDate) data.append({'id':item.id, 'CaseNumber':item.CaseNumber,'Title':item.Title.Description, 'Category': item.CaseCategory.Description, 'CreatedDate':localtime,'Users':item.Users.first_name+' '+item.Users.last_name, 'AssignedUser':item.AssignedUser.first_name+' '+item.AssignedUser.last_name, 'Status':item.Status.Description }) response_data = {'itemlist': data} return HttpResponse(json.dumps(response_data)) def datetime_handler(x): if isinstance(x, datetime.datetime): return x.isoformat() raise TypeError("Unknown type") json.dumps(data, default=datetime_handler) ajax $.ajax({ type: 'POST', url: 'GetCustomerCases', dataType: 'json', data: { TcNO: TcNO, csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(), }, success: function (data) { console.log(data); for (var i = 0; i < data.itemlist.length; i++) { $('#CustomerCases tbody').append('<tr>' + '<td>' + "<a href= /Case/" + data.itemlist[i]['id']+ '>'+ data.itemlist[i]['CaseNumber'] + '</a></td>' + '<td>' + data.itemlist[i]['Title'] + '</td>' + '<td>' + data.itemlist[i]['Category'] + '</td>' + '<td>' + data.itemlist[i]['CreatedDate']+ '</td>' + '<td>' + data.itemlist[i]['Users'] + '</td>' + '<td>' + data.itemlist[i]['AssignedUser'] + '</td>' + '<td>' + data.itemlist[i]['Status'] + '</td>' + '<td>' + data.itemlist[i]['CreatedDate'] + '</td>' + '</tr>'); } }, }); I'm able to get my cases object via ajax but this datetime field looks like "2017-10-17T10:27:46.862951+00:00" in html. Simply how can i convert to "10 october 2017 10:27 am". Also is there any way to use django template tags like {{ |timesince }} in javascript append. -
How to Restart Celery Wroker ran by Supervisord
I am running celery on production using supervisord. My supervisor configuration is below. [program:celeryd] command=%(ENV_PROJECT_PATH)s/scripts/celery_worker.sh stdout_logfile=%(ENV_PROJECT_PATH)s/celeryd.log stderr_logfile=%(ENV_PROJECT_PATH)s/celeryd.log autostart=true autorestart=true startsecs=10 stopwaitsecs=1000 priority=1000 My command to run celery worker is celery_path=$(which celery) $celery_path -A Project_Name worker --loglevel=info I want to ask, how to restart celery worker when my codebase changes in production? -
Django: Connect to external database with changing host/port
I need to connect django to an external database. Sometimes the host of the database is changed (lets say old host dies and I need to connect to a new host dynamically). I have monkey patched mysql_query to come up with following re-try logic (taken from https://stackoverflow.com/a/34275180/8793815) try: query_mysql() catch DatabaseError as e: new_host = get_new_db_host() update_django_database_setting(new_host) //settings.DATABASE re_initialize_django_db_and_or_connections() //**Not sure how to do this** query_mysql() I need to do this to make sure all the queries are served even when DB changes. I cannot start/stop django to do this. Database host changes are dynamic and not known apriori. (Context about how DB host can change. The DB I am trying to connect is a cluster of Master-Slave databases. Hosts change when DBAs are doing maintenance by promoting Slave to Master or adding new slaves) -
Migrating development database onto Heroku with Django
I am having trouble migrating my development database onto Heroku. This is for a personal project written in Django. settings.py db_from_env = dj_database_url.config() DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } DATABASES['default'].update(db_from_env) I've migrated the database locally and pushed the migration onto Heroku already. Then, I ran the heroku run python manage.py migrate command to migrate the database on Heroku. I had accidentally ran makemigrations on Heroku, but have restarted my dynos since. Currently, my database on Heroku is not populated at all.